Rai*_*Man 0 loops for-loop r write.table
我有几个变量如下:
cats <- "some long text with info"
dogs <- "some long text with info"
fish <- "some long text with info"
....
Run Code Online (Sandbox Code Playgroud)
我手动将这些变量的内容写入文本文件:
write.table(cats, "info/cats.txt", sep="\t")
write.table(dogs, "info/dogs.txt", sep="\t")
....
Run Code Online (Sandbox Code Playgroud)
我阅读了这个问题的答案,并尝试编写一个循环来自动编写文件.
所以我创建了一个列表:
lst <<- list(cats, dogs,fish, ....)
Run Code Online (Sandbox Code Playgroud)
然后遍历列表:
for(i in seq_along(lst)) {
write.table(lst[[i]], paste(names(lst)[i], ".txt", sep = ""),
col.names = FALSE, row.names = FALSE, sep = "\t")
}
Run Code Online (Sandbox Code Playgroud)
但上面迭代的输出是一个调用的文本文件.txt,它包含列表中最后一个变量的内容.
任何想法为什么上述循环不能按预期工作?
请注意以下事项:
> 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
Run Code Online (Sandbox Code Playgroud)
当您创建列表时,您没有给它任何名称,因此您的循环没有任何可用的东西.修复:
> names(lst) <- c("cats", "dogs", "fish")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1427 次 |
| 最近记录: |