Contents
実行環境
- Windows
7 32bit + R Portable 3.1.2 - ConEmu Build 150513
で Rterm.exeを使用
ファイルの例
作業としては、先日、更新時刻順でファイルリストを作った続きです。「数値がスペース区切りで入ってる」と聞いていたファイルを、とりあえず実際の中身は載せられないので簡単なダミーで示すと ↓ こんな感じ。二つ目の画像は
R で、NULL 文字をスキップして 1 行ずつベクトルに入れる
ファイル読み込みの関数・方法はいろいろですが、今回は(1)readLinesrows = readLines('R:/TMP/all.prn', skipNul=T) print(rows) [1] "1 1 1 1 1 1 1 1 1 1" [2] "2 2 2 2 2 2 2 2 2 2" [3] "3 3 3 3 3 3 3 3 3 3" [4] "4 4 4 4 4 4 4 4 4 4" [5] "5 5 5 5 5 5 5 5 5 5" [6] "6 6 6 6 6 6 6 6 6 6" [7] "7 7 7 7 7 7 7 7 7 7" [8] "8 8 8 8 8 8 8 8 8 8" [9] "9 9 9 9 9 9 9 9 9 9"
mat = t(sapply(strsplit(rows, ' '), as.numeric)) print(mat) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 1 1 1 1 1 1 1 1 1 [2,] 2 2 2 2 2 2 2 2 2 2 [3,] 3 3 3 3 3 3 3 3 3 3 [4,] 4 4 4 4 4 4 4 4 4 4 [5,] 5 5 5 5 5 5 5 5 5 5 [6,] 6 6 6 6 6 6 6 6 6 6 [7,] 7 7 7 7 7 7 7 7 7 7 [8,] 8 8 8 8 8 8 8 8 8 8 [9,] 9 9 9 9 9 9 9 9 9 9
以下は(2)での少し違う書き方。sapply
do.call(rbind, lapply(strsplit(rows, ' '), as.numeric))
まず文字型のまま
mat = do.call(rbind, strsplit(rows, ' ')) apply(mat, 2, as.numeric)
普通のプログラミング言語のように
lis = strsplit(rows, ' ') mat = NULL for (i in 1:length(lis)) { mat = rbind(mat, as.numeric(lis[[i]])) } print(mat)
ファイル読み込みで失敗した例
NULLreadLines('R:/TMP/all.prn') [1] "1 1 1 1 1 1 1 1 1 1" "" "" [4] "" "" "" [7] "" "" "" [10] "" Warning messages: 1: In readLines("R:/TMP/all.prn") : line 2 appears to contain an embedded nul 2: In readLines("R:/TMP/all.prn") : line 3 appears to contain an embedded nul 3: In readLines("R:/TMP/all.prn") : line 4 appears to contain an embedded nul 4: In readLines("R:/TMP/all.prn") : line 5 appears to contain an embedded nul 5: In readLines("R:/TMP/all.prn") : line 6 appears to contain an embedded nul 6: In readLines("R:/TMP/all.prn") : line 7 appears to contain an embedded nul 7: In readLines("R:/TMP/all.prn") : line 8 appears to contain an embedded nul 8: In readLines("R:/TMP/all.prn") : line 9 appears to contain an embedded nul 9: In readLines("R:/TMP/all.prn") : line 10 appears to contain an embedded nul 10: In readLines("R:/TMP/all.prn") : incomplete final line found on 'R:/TMP/all.prn'
read.table
read.table('R:/TMP/all.prn', sep=' ') V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 1 1 1 1 1 1 1 1 1 1 1 2 NA 6 6 6 6 6 6 6 6 6 3 NA 7 7 7 7 7 7 7 7 7 4 NA 8 8 8 8 8 8 8 8 8 5 NA 9 9 9 9 9 9 9 9 9 Warning messages: 1: In read.table("R:/TMP/all.prn", sep = " ") : line 2 appears to contain embedded nulls 2: In read.table("R:/TMP/all.prn", sep = " ") : line 3 appears to contain embedded nulls 3: In read.table("R:/TMP/all.prn", sep = " ") : line 4 appears to contain embedded nulls 4: In read.table("R:/TMP/all.prn", sep = " ") : line 5 appears to contain embedded nulls 5: In scan(file = file, what = what, sep = sep, quote = quote, dec = dec, : embedded nul(s) found in input
もしファイルに
ところで、今日の記事用にNULL