【问题标题】:Read, subset and bind many .txt files in R [duplicate]在 R [重复] 中读取、子集和绑定许多 .txt 文件
【发布时间】:2021-10-13 13:45:53
【问题描述】:

我想阅读许多 .txt 文件,忽略第一行,只获取第五列。之后,将提取的所有这些列合并到一个 data.frame 中。

我使用 for 循环创建了这些,使用 assign() 构建了许多变量,然后使用 mget(ls()) 获取所有变量。

有没有更快的方法来做到这一点?

以下是其中三个文件:we.tl/t-JcVsfiUPLv

【问题讨论】:

  • 您可以包含您当前拥有的代码。

标签: r


【解决方案1】:

assign 通常应该避免使用,在这种情况下,我们不需要在全局环境中创建这些对象。尝试使用lapply

#List all text files in the working directory
filenames <- list.files(pattern = '\\.txt$')
#Read every text file with header, skipping the 1st row. 
#Keep only the 5th column after reading the data. 
result <- lapply(filenames, function(x) read.table(x,skip = 1,header = TRUE)[,5])
result

【讨论】:

  • 感谢您的回答!然后我会使用像cbind这样的东西?我仍然需要将这些向量加入一个表中
  • do.call(cbind, result) ?
猜你喜欢
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多