R通过for循环用变量写入文件

标签 r for-loop

我正在尝试使用 R 编写许多带有变量的 txt 文件。

这是一个向量

name <- c("Apple","Banana","Cat")

我想在 R 中使用 for 循环来分配值并将值用作文件名的一部分。

for (i in length(name)){

"The name is i"    

assign(paste(name, i, sep = ""), i)

write.table("i.txt")

}

我的期望是生成三个txt文件

Apple.txt
Banana.txt
Cat.txt

每个txt文件的上下文分别是一个句子。

The name is Apple
The name is Banana
The name is Cat

最佳答案

如果目标是编写三个.txt 文件,我们不需要assign 来创建一些全局对象。遍历name直接用sprintfpaste创建值,然后写入.txt文件

for (nm in name){

 val <- sprintf("The name is %s", nm)
 #or with `paste`
 #val <- paste0("The name is ", nm)

 #write.table(val, file = paste0(nm, ".txt"))
 #this can also be with `write` that will not generate the heading
 write(val, file = paste0(nm, ".txt"))
}

write.table之所以返回两行是因为转换为data.frame。根据?write.table描述

write.table prints its required argument x (after converting it to a data frame if it is not one nor a matrix) to a file or connection.

关于R通过for循环用变量写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43648424/

相关文章:

r - 当我使用函数创建 R data.frame 时,如何向 R data.frame 添加属性?

r - 如何平衡不平衡分类1 :1 with SMOTE in R

c++ - 我的列表控件需要一个 while 循环

python - 关于在python中迭代函数的问题

java - 在线程内使用 for 循环与类似的 while 循环行为不匹配

r - R中的极坐标变换图像

r - 如何安全地向运行 R 脚本的 Azure 批处理服务提供 secret

r - R “for loop”错误消息{}

java - 如何在java中延迟循环点数组?

r - 在 R 中寻找模式