我正在尝试使用 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
直接用sprintf
或paste
创建值,然后写入.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/