R使用for循环的变量写入文件

R使用for循环的变量写入文件,r,for-loop,R,For Loop,我正在尝试使用R编写许多带有变量的txt文件 这是一个向量 name <- c("Apple","Banana","Cat") 我的期望是生成三个txt文件 Apple.txt Banana.txt Cat.txt 每个txt文件的上下文分别是一个句子 The name is Apple The name is Banana The name is Cat 如果目标是编写三个.txt文件,则不需要assign来创建一些全局对象。循环使用名称直接使用sprintf或粘贴创建值,然后将其

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

这是一个向量

name <- c("Apple","Banana","Cat")
我的期望是生成三个txt文件

Apple.txt
Banana.txt
Cat.txt
每个txt文件的上下文分别是一个句子

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

如果目标是编写三个
.txt
文件,则不需要
assign
来创建一些全局对象。循环使用
名称
直接使用
sprintf
粘贴
创建值,然后将其写入
.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"))
}
for(名称为nm){

val你能解释一下为什么文件中有两行吗?第一行是“x”,第二行是“1”。名称是Apple“@user3631848。只需将table
更改为
write
,你就只有一行了。我以为你想要一个列标题
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"))
}