« 2023年7月 | トップページ | 2023年9月 »

2023年8月31日 (木)

[R]正規表現のマッチをテストする

stringrパッケージのstr_view関数を使う。str_viewは引数に文字列型ベクトルだけを与えると、その中身を表示するだけで、第2引数にパターンを指定すると、そのパターンにマッチする要素だけを表示し、どこがマッチしているのかわかるように表示してくれる。

> library(stringr)
> s <- c("ABC", "ABc", "Abc", "abc")
> str_view(s)
[1] | ABC
[2] | ABc
[3] | Abc
[4] | abc
> str_view(s, "B")
[1] | A<B>C
[2] | A<B>c
> str_view(s, "bc$")
[3] | A<bc>
[4] | a<bc>
> str_view(s, "[A-Z]{4}")
> str_view(s, "[A-Z]{2}")
[1] | <AB>C
[2] | <AB>c

2023年8月30日 (水)

[Excel VBA]CSVファイルを高速で読み込む

QueryTablesオブジェクトのAddメソッドを使う。まずは動作確認のための巨大なCSVファイル(qt.csv)を作成する。PowerShellで以下のコマンドを実行すると100万行からなるCSVファイル(ファイルサイズ11,000,000バイト(約10.5メガバイト))が作成される。

PS > "A,B,C,1,2`r`n" * 1000000 | Out-File -Encoding default -NoNewline qt.csv
PS > Get-ChildItem .\qt.csv
ディレクトリ: ○○○
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2023/07/01 22:33 11000000 qt.csv
PS > Get-Content -path .\qt.csv -TotalCount 3
A,B,C,1,2
A,B,C,1,2
A,B,C,1,2

以下のプログラムを実行する。ワークシートSheet1の中身を強制的にすべて削除し、A1セルからファイルの中身を強制的に入力するので注意。

Dim filepath As String
Dim ws As Worksheet
Dim qt As QueryTable
Dim dtstart As Date
Dim dtend As Date
filepath = Application.ThisWorkbook.Path & "\qt.csv"
Set ws = Worksheets("Sheet1")
ws.Cells.Clear
dtstart = Time
Debug.Print "開始時刻: " & dtstart
Set qt = ws.QueryTables.Add(Connection:="TEXT;" & filepath, Destination:=ws.Range("A1"))
With qt
.TextFileCommaDelimiter = True
.TextFileParseType = xlDelimited
.TextFilePlatform = 932
.RefreshStyle = xlOverwriteCells
.Refresh
.Delete
End With
dtend = Time
Debug.Print "終了時刻: " & dtend
Debug.Print "処理時間: " & DateDiff("s", dtstart, dtend) & "秒"

イミディエイトの出力

開始時刻: 23:26:05
終了時刻: 23:26:11
処理時間: 6秒

Qt

10.5メガバイトのCSVファイルを約6秒で読み込んで各セルに入力していることが分かる。

2023年8月29日 (火)

[R]正規表現による文字列の比較

stringrパッケージのstr_detect関数を使う。str_detect関数はマッチしたらTRUE、そうでなければFALSEを返すので、要素の数が一つの文字列型ベクトルを与えれば、文字列の比較に使うことが出来る。

> library(stringr)
> s <- c("ABC", "ABCD", "BCD", "CD")
> str_detect(s, "^AB")
[1] TRUE TRUE FALSE FALSE
> str_detect(s, "CD$")
[1] FALSE TRUE TRUE TRUE
> if (str_detect("BCD", "^AB")) {cat("OK\n")}
> if (str_detect("ABC", "^AB")) {cat("OK\n")}
OK

2023年8月28日 (月)

[R]正規表現による文字列の比較

grepl関数を使う。grepl関数はマッチしたらTRUE、そうでなければFALSEを返すので、要素の数が一つの文字列型ベクトルを与えれば、文字列の比較に使うことが出来る。

> s <- c("ABC", "ABCD", "BCD", "CD")
> grepl("^AB", s)
[1] TRUE TRUE FALSE FALSE
> grepl("CD$", s)
[1] FALSE TRUE TRUE TRUE
> if (grepl("^AB", "BCD")) {cat("OK\n")}
> if (grepl("^AB", "ABC")) {cat("OK\n")}
OK

2023年8月27日 (日)

[R]データフレームをtibbleに変換する

as_tibble関数を使う。

> library(tibble)
> no <- 1:4
> name <- c("AB", "12", "あい", "阿井")
> weight <- c(1.2, 2.3, 3.4, 4.5)
> dtf <- data.frame(no, name, weight)
> print(dtf)
no name weight
1 1 AB 1.2
2 2 12 2.3
3 3 あい 3.4
4 4 阿井 4.5
> tbl <- as_tibble(dtf)
> print(tbl)
# A tibble: 4 x 3
no name weight
  <int> <chr> <dbl>
1 1 AB 1.2
2 2 12 2.3
3 3 あい 3.4
4 4 阿井 4.5
> class(dtf)
[1] "data.frame"
> class(tbl)
[1] "tbl_df" "tbl" "data.frame"

2023年8月25日 (金)

[R]スクリプト内で処理時間を計算して表示する

開始時と終了時にそれぞれSys.time関数で現在の日時を取得し、最後にdifftime関数でその差を計算して表示すればよい。以下をスクリプトファイルdifftime.Rに保存をして、実行してみる。途中にSys.sleep関数を使用して意図的に3秒間処理を止めている。

dtibegin <- Sys.time()
Sys.sleep(3)
dtiend <- Sys.time()
d <- difftime(dtiend, dtibegin, units = "secs")
cat(sprintf("処理時間: %.2f秒\n", d))

実行結果

> source("difftime.R")
処理時間: 3.07秒

2023年8月24日 (木)

[R]tibbleを作成する

tibble関数を使う。tibbleはデータフレームに類似した機能を提供するが、データフレームよりもいろいろと便利な機能を提供する。

> library(tibble)
> no <- 1:4
> name <- c("AB", "12", "あい", "阿井")
> weight <- c(1.2, 2.3, 3.4, 4.5)
> tbl <- tibble(no, name, weight)
> print(tbl)
# A tibble: 4 x 3
no name weight
  <int> <chr> <dbl>
1 1 AB 1.2
2 2 12 2.3
3 3 あい 3.4
4 4 阿井 4.5
> dim(tbl)
[1] 4 3
> dim(tbl)[2]
[1] 3
> tbl[1, 2]
# A tibble: 1 x 1
name
  <chr>
1 AB
> tbl[2, 3]
# A tibble: 1 x 1
weight
  <dbl>
1 2.3
> tbl[3, ]
# A tibble: 1 x 3
no name weight
  <int> <chr> <dbl>
1 3 あい 3.4
> tbl[, 3]
# A tibble: 4 x 1
weight
  <dbl>
1 1.2
2 2.3
3 3.4
4 4.5
> tbl$name
[1] "AB" "12" "あい" "阿井"
> tbl$name[3]
[1] "あい"

2023年8月22日 (火)

[R]サイズが非常に大きなテキストファイルを簡単に作成する

動作確認でサイズが非常に大きなテキストファイルが必要なときがあるが、文字型ベクトルを使うと簡単に作成することができる。

以下は、Windows環境でサイズが5億バイト(≒476.8MB)のファイルを、一つのコマンドで作成している。10バイトの文字列("AB12あい"の8バイトと改行コードCR+LFの2バイト)を5,000万個作り、それをテキストファイルに出力している。文字コードはシフトJIS、改行コードはCR+LFとしているため、サイズが単純に10バイト×5,000万=5億バイトとなっている。作成には10分弱要している。

> cat(rep("AB12あい", 5 * 10 ^ 7), file = "temp.txt", sep = "\n")
> dir(".", "temp\\.txt")
[1] "temp.txt"
> file.size("temp.txt")
[1] 5e+08

2023年8月14日 (月)

[R]文字列型ベクトルを簡単にテキストファイルに出力する

cat関数を使う。sepオプションには文字型ベクトルの各要素の間に挟む文字列を指定する。以下の例では、最後のコマンドを実行後にはプロンプトは改行されないで表示される。

> lns <- c("ABC", "123", "あい")
> cat(lns, file = "temp.txt", sep = "\n")
> shell("type temp.txt")
ABC
123
あい
> cat(lns, file = "temp.txt", sep = ",")
> shell("type temp.txt")
ABC,123,あい

2023年8月 5日 (土)

[R]単純集計を行う

table関数を使う。excludeオプションを使うことで、特定の値を集計から除くことが出来る。

> name <- c("A", "A", "A", "A", "B", "B", "C")
> print(name)
[1] "A" "A" "A" "A" "B" "B" "C"
> table(name)
name
A B C
4 2 1
> table(name, exclude = "B")
name
A C
4 1

戻り値はテーブル形式のため、集計結果の中身を個別に扱うには、データフレームに変換する。

> dtf <- as.data.frame(table(name))
> print(dtf)
name Freq
1 A 4
2 B 2
3 C 1
> dtf[3, 2]
[1] 1
> sum(dtf[, 2])
[1] 7

2023年8月 1日 (火)

[R]λ=1のときのポアソン分布(「統計解析のはなし」(東京図書)pp.93-94)

> # 確率変数 X=x
> x <- 0:6
> # λ = 1
> lam <- 1
> # λ = 1 のときのポアソン分布
> pp <- lam ^ x / factorial(x) * exp(-lam)
> # 計算結果の表示
> print(data.frame(X = x, P = pp))
X P
1 0 0.3678794412
2 1 0.3678794412
3 2 0.1839397206
4 3 0.0613132402
5 4 0.0153283100
6 5 0.0030656620
7 6 0.0005109437

« 2023年7月 | トップページ | 2023年9月 »

無料ブログはココログ

■■

■■■