2016-07-13 10 views
2

Rで読み込むテキストファイルがありますが、そのファイルはタブで区切られていないようです。ファイルの唯一の構造は、ある時点で列が常に終了する(つまり、列が右揃えになる)ことです。"right-aligned"データを含むread.table

まず、このタイプのデータ構造の名前はありますか?それでは、どのようにRでそれを読むことができますか?ただ、()は動作しません、欠損値を適切な場所に置かれることはありませんread.tableを使用して

2.37  2.03       2.38 
    5,397  5,082       5,609 
    13.0  21.6   15.2   15.2 
    128.0  103.1   134.2   133.4 

...

# download data: 
tmp <- tempfile() 
f <- download.file("http://usda.mannlib.cornell.edu/usda/waob/wasde//1990s/1995/wasde-01-12-1995.txt", tmp) 
D <- file(tmp) 
data_enc <- readLines(D, warn=FALSE) 
close(D) 
dat <- sapply(strsplit(data_enc[232:236], ":"), function(x) x[2]) 
writeLines(dat, tmp) 

## try to read data: 
read.table(tmp, fill = TRUE, sep ="", header=FALSE) 

は与える:

 V1 V2 V3 V4 
1 2.37 2.03 2.38 NA 
2 5,397 5,082 5,609 NA 
3 13.0 21.6 15.2 15.2 
+0

関連記事:http://stackoverflow.com/questions/24715894 – zx8754

答えて

1

たぶんread.fwfを使用して、固定幅のフォーマットされたデータの表を読み取ろうとしてください:

widths <- gregexpr("\\.\\d", readLines(tmp)[5])[[1]]+1L # line 5 looks complete 
widths <- c(widths[1], diff(widths)) # posis after the decimal points as widths 
read.fwf(tmp, widths = widths) 
#   V1   V2 V3    V4 
# 1  2.37  2.03 NA    2.38 
# 2 5,397  5,082 NA   5,609 
# 3  13.0  21.6 15.2    15.2 
# 4 128.0  103.1 134.2   133.4 
# 5 146.4  130.9 156.5   155.7 
+1

よかった!このデータはまだ固定幅のデータですか?私は固定幅が同じ終わりだけでなく、同じスタートを含むと思うことによってだまされました!それでは、おそらくHadleyのパッケージリーダーは、それをとても簡単にするでしょう:read_fwf(tmp、fwf_empty(tmp)) – Matifou

+0

...うん、それはさらに良い。 :-) – lukeA

関連する問題