使用循环在R中写入文件 [英] Write to files in R using a loop

查看:483
本文介绍了使用循环在R中写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个变量如下:

$ p $ cats< - 一些带有信息的长文本
狗< - 一些带有信息的长文本
fish < - 一些带有信息的长文本
....

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

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

我读到,并试图编写一个循环来自动写入文件。所以我创建了一个列表:

  lst << - 列表(猫,狗,鱼,....)

然后遍历列表:


$ b $ pre $ 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 ,它包含列表中最后一个变量的内容。



任何想法为什么上面的循环不能按预期工作?

解决方案

注意以下几点:

 >猫<  - 一些长信息
>狗< - 一些带有信息的长文本
>鱼< - 一些长信息的文本
> lst < - 列表(猫,狗,鱼)#不是< -
> names(lst)
NULL

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

 >名称(lst)< -c(cats,dogs,fish)


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?

解决方案

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")

这篇关于使用循环在R中写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆