【问题标题】:Write to files in R using a loop使用循环写入 R 中的文件
【发布时间】:2016-06-22 23:05:46
【问题描述】:

我有几个变量如下:

cats <- "some long text with info"
dogs <- "some long text with info"
fish <- "some long text with info"
....

我手动将这些变量的内容写入一个文本文件:

write.table(cats, "info/cats.txt", sep="\t")
write.table(dogs, "info/dogs.txt", sep="\t")
....

我阅读了this question 的答案并尝试编写一个循环来自动写入文件。

所以我创建了一个列表:

lst <<- list(cats, dogs,fish, ....)

然后遍历列表:

for(i in seq_along(lst)) {
    write.table(lst[[i]], paste(names(lst)[i], ".txt", sep = ""), 
               col.names = FALSE, row.names = FALSE,  sep = "\t")
}

但上述迭代的输出是一个名为.txt 的文本文件,它包含列表中最后一个变量的内容。

知道为什么上述循环没有按预期工作吗?

【问题讨论】:

  • is.null(names(lst)); #[1] TRUE
  • @nrussell 返回TRUE
  • 是的——你没有列出你的名单。等效地,paste0(NULL, ".txt")

标签: r loops for-loop write.table


【解决方案1】:

注意以下几点:

> cats <- "some long text with info"
> dogs <- "some long text with info"
> fish <- "some long text with info"
> lst <- list(cats, dogs,fish)  # not <<-
> names(lst)
NULL

当你创建你的列表时,你没有给它任何名字,所以你的循环没有任何东西可以使用。修复:

> names(lst) <- c("cats", "dogs", "fish")

【讨论】:

  • 谢谢,我以为名字是自动从列表中选择出来的
  • 命名参数将成为列表名称,例如,list = list(cats = cats, name_of_dog_item = dogs, fish_here = fish) 将具有名称 "cats""name_of_dog_item" 等。
  • 或者,mget 将自动命名您的列表:mget(c("cats", "dogs", "fish"))
  • @HongOoi 是否也可以为第一部分创建循环?
猜你喜欢
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多