0

単純なデータの再フォーマットに関する質問だと思われるものがあります。データ ファイル (txt) は、観測番号が行ごとに区切られた構造になっています。

1
45 65
78 56
2
89 34
39 55

望ましい出力は、

1 45 65
1 78 56
2 89 34
2 39 55

その変換を行う方法に関する提案をいただければ幸いです。ありがとう。

4

1 に答える 1

1

でファイルを読み取ることができましたreadLines。インデックス変数を作成し、「行」を分割します。リスト要素の最初の要素を削除しread.table、ファイルを読み取るために使用し、unnest

 lines <- readLines('file.txt')
 library(stringr)
 #remove leading/lagging spaces if any 
 lines <- str_trim(lines) 
 #create the index mentioned above based on white space 
 indx  <- !grepl('\\s+', lines)
 #cumsum the above index to create grouping
 indx1 <- cumsum(indx)
 #split the lines with and change the names of the list elements 
 lst <- setNames(split(lines, indx1), lines[indx])
 #Use unnest after reading with read.table 
 library(tidyr)
 unnest(lapply(lst, function(x) read.table(text=x[-1])), gr)
 #   gr V1 V2
 #1  1 45 65
 #2  1 78 56
 #3  2 89 34
 #4  2 39 55

または、アプローチMapから使用できますbase R

 do.call(rbind,Map(cbind, gr=names(lst), 
             lapply(lst, function(x) read.table(text=x[-1]))))
于 2015-07-16T20:42:25.677 に答える