【问题标题】:To replace a string within a for loop in R [duplicate]在R中的for循环中替换字符串[重复]
【发布时间】:2017-08-15 22:19:27
【问题描述】:

我有很多文本文件

fr.txt
no.txt
sta.txt
sto.txt

我创建了一个文件名作为字符串的向量

string <- c("fr","no","sta","sto")

我想在 R 中使用 for 循环来使用字符串作为变量名并读取相应的文件。

for (type in c("fr","no","sta","sto")){type <- read.table(sprintf("%s.txt", type),header=TRUE)}

例如

fr <- read.table("fr.txt",header=TRUE)
no <- read.table("no.txt",header=TRUE)
sta <- read.table("sta.txt",header=TRUE)

我应该如何开始?上面的 for 循环没有做我想做的事。

【问题讨论】:

  • “上面的 for 循环没有做我想要的。” -- 这意味着什么具体?此外,您在read.table(sprintf("%s.txt", type) header=TRUE) 中的header = TRUE 之前缺少一个逗号。
  • 查看 gregor 对this post 的回答,了解一些可能有帮助的提示。
  • 不要使用不同的变量名,使用列表。
  • L &lt;- lapply(paste0(type,".txt"), read.table, header=TRUE) 给出数据帧列表。 names(L) &lt;- type 设置名称。

标签: r string for-loop


【解决方案1】:

如果您想读取目录中的所有“.txt”文件,只需使用:

temp = list.files(pattern="*.txt")
myfiles = lapply(temp, read.table)

解释
list.files() - 抓取您工作目录中的文件。假设您将文件(“one.txt”、“two.txt”等)保存在“C://example”中,那么您必须首先设置您的工作目录,例如

setwd("C://example")
以便 list.files() 知道在哪里搜索您的文件。如果需要,您还可以使用以下方法列出 .csv 文件:
temp = list.files(pattern="*.csv")

接下来,您可以使用以下方法为工作目录中的每个“.txt”文件应用 read.table 函数:

lapply(temp, read.table)

【讨论】:

  • 它将读取所有 *.txt 文件,这不是我所期望的。我只想读取我指定的文件。
  • 所以你可以使用 temp = c("one.txt","two.txt"); myfiles = lapply(temp, read.table)
【解决方案2】:

试试这个:

for (type in c("fr","no","sta","sto")){
      as.name(type) <- read.table(paste0(type,".txt"), header=TRUE)
}

【讨论】:

  • 谢谢,但我收到错误“as.name(type)
  • 我很抱歉,试试这个for (type in c("fr","no","sta","sto")){ eval(parse(text = paste0(type,"&lt;-read.table(\"",type,".txt","\",header=TRUE)"))) }
  • 这样的另一个解决方案for (type in c("fr","no","sta","sto")){ assign(type,read.table(paste0(type,".txt"))) }
猜你喜欢
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
相关资源
最近更新 更多