【问题标题】:read.table with "right-aligned" data具有“右对齐”数据的 read.table
【发布时间】:2016-11-15 16:51:01
【问题描述】:

我有一个要在 R 中读取的文本文件,但该文件似乎不是制表符分隔的。文件的唯一结构是列总是在某个点结束(即列右对齐)。

那么,首先,这种数据结构有名称吗?那么,如何在 R 中读取呢?

    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

只使用 read.table() 不起作用,缺失的值不会放在正确的位置...

# 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

【问题讨论】:

标签: r read.table data-import


【解决方案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

【讨论】:

  • 哦,太好了!那么这个数据还是定宽数据吗?我被认为固定宽度不仅涉及相同的结束而且涉及相同的开始而被欺骗了!?那么也许Hadley的包阅读器会很容易:read_fwf(tmp, fwf_empty(tmp))
  • ...是的,甚至更好。 :-)
猜你喜欢
  • 1970-01-01
  • 2011-06-25
  • 2012-07-15
  • 2015-06-15
  • 2016-09-04
  • 2013-09-13
  • 2011-03-31
  • 2020-11-20
  • 2010-11-26
相关资源
最近更新 更多