rbind 具有不同行长的文本文件

标签 r

我正在尝试使用 dif.length of rows rbind 两个 txt 文件,例如:

我使用这个代码:

a<-matrix(1:12,4,3)
b<-matrix(21:41,7,3)

setwd("test/")
write.table(a, file="a.txt",quote=FALSE,  row.names=FALSE,col.names=FALSE)
write.table(b, file="b.txt",quote=FALSE, row.names=FALSE, col.names=FALSE)
file_list <- list.files()
g<- do.call(rbind,lapply(file_list,FUN=function(files){scan(files,what = character())}))

我有这个警告信息:

“在(函数(...,deparse.level = 1)中:
结果的列数不是向量长度的倍数(arg 1)”

我希望 g 看起来像这样:
##       [,1] [,2] [,3]
##  [1,]    1    5    9
##  [2,]    2    6   10
##  [3,]    3    7   11
##  [4,]    4    8   12
##  [5,]   21   28   35
##  [6,]   22   29   36
##  [7,]   23   30   37
##  [8,]   24   31   38
##  [9,]   25   32   39
## [10,]   26   33   40
## [11,]   27   34   41

有什么解决方案,因为我是新的 i R 吗?
非常感谢,

最佳答案

除非另有说明,scan()将整个文件作为单个原子向量读取。您可以将列表传递给 what参数,但使用读取结构化数据的函数更容易、更安全。此外,您不想使用 what = character()因为您正在读取数值。
read.table()在基数 R 中,和 fread()从包“data.table”可以很容易地做到这一点。

files <- c("a.txt", "b.txt")

## read.table()
data.matrix(do.call(rbind, lapply(files, read.table)), rownames.force = FALSE)

## fread()
library(data.table)
data.matrix(rbindlist(lapply(files, fread)))

这两个都返回矩阵
#       V1 V2 V3
#  [1,]  1  5  9
#  [2,]  2  6 10
#  [3,]  3  7 11
#  [4,]  4  8 12
#  [5,] 21 28 35
#  [6,] 22 29 36
#  [7,] 23 30 37
#  [8,] 24 31 38
#  [9,] 25 32 39
# [10,] 26 33 40
# [11,] 27 34 41

如果您真的想使用 scan() ,您可以将列表传递给 what参数告诉它列数。
## get number of columns
nc <- max(unlist(lapply(files, count.fields)))
## read as a list, then bind together
do.call(rbind, lapply(files, function(x) {
    do.call(cbind, scan(x, what = as.list(double(nc)), quiet = TRUE))
}))
#       [,1] [,2] [,3]
#  [1,]    1    5    9
#  [2,]    2    6   10 
#  [3,]    3    7   11
#  [4,]    4    8   12
#  [5,]   21   28   35
#  [6,]   22   29   36
#  [7,]   23   30   37
#  [8,]   24   31   38
#  [9,]   25   32   39
# [10,]   26   33   40
# [11,]   27   34   41

但这只是count.fields()然后 scan() ,这基本上是什么 read.table()一步一个脚印。此外,如果数据中存在缺失值,这可能会带来风险。

关于rbind 具有不同行长的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28705060/

相关文章:

r - 为什么当我给 R 中的两个列表元素赋予相同名称时没有错误

r - 多元 GARCH 包

r - 按包含元素列表的变量中的元素对数据框进行分组

r - 从数据框创建数据框

r - 如何在R中将一行拆分为3个较短的行

r - 大数据的kmeans

r - 使用 mutate_at 创建新变量,同时保留原始变量

r - ggplot 在一个图例中使用 "colour"和 "fill"作为 astetic 到同一时间

r - 使用knitr在beamer中叠加动画

r - 无法在 ggplot2 上绘制比例尺或指北针