Write to files in R using a loop

旧巷老猫 提交于 2019-12-13 07:04:01

问题


I have several variables as follow:

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

and I manually write the content of these variables into a text file:

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

I read the answer to this question and tried to write a loop to automatically write the files.

So I created a list:

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

and then iterated through the list:

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

but the output of the above iteration is one text file called .txt and it contains the content of the last variable in the list.

any idea why the above loop doesn't work as expected?


回答1:


Note the following:

> 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

When you created your list, you didn't give it any names, so your loop doesn't have anything to work with. A fix:

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


来源:https://stackoverflow.com/questions/35876929/write-to-files-in-r-using-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!