带有 "right-aligned"数据的 read.table

标签 r read.table data-import

我有一个文本文件要在 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

最佳答案

也许可以尝试使用 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

关于带有 "right-aligned"数据的 read.table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38345932/

相关文章:

r - 在 R 中提取字符串之前的数值

python - Python 中 R 的 read.table 等价物

R 从带有 csv 文件内容的内联字符串中读取 .csv 数据

elasticsearch - 从Oracle导入数据(初始加载)到Elastic Search的最佳方法

r - 比较如果条件满足,则重置序列的有效方法( R )

r - 创建十六进制图

java - 快速简便的数据导入工具/库

重新格式化数值而不强制转换为字符

hadoop - 使用Sqoop --query将数据从MySQL导入到HBase时出错?