在R中使用不同的文件名编写多个表格。

huangapple go评论65阅读模式
英文:

write multiple table with different filename in R

问题

我有多个表格想要以原始名称保存为CSV文件。
这是我的示例: df.a01,df.a02,df.a03,etc.

我尝试过以下代码:

list <- list(df.a01, df.a02, df.a03)

for (i in 1:length(list)) {
  write.csv(list[i], paste0(i, '.csv'), row.names = FALSE)
}

但它不起作用。

我得到了1.csv,2.csv,3.csv,但我想要的是a01.csv, a02.csv, a03.csv

我还尝试过https://stackoverflow.com/questions/72800045/save-several-data-frames-with-different-names-with-loop,仍然无法得到我想要的结果。

非常感谢任何帮助。

英文:

I have multiple tables want to save them as csv with original names.
Here is my example : df.a01,df.a02,df.a03,etc.

I tried

list &lt;- list(df.a01,df.a02,df.a03)

for (i in 1:length(list)) {
  write.csv(list[i], paste0(i, &#39;.csv&#39;), row.names = FALSE)
}

but it's not work.

I got 1.csv,2.csv,3.csv,but I want to is like a01.csv,a02.csv,a03.csv.

I also tried https://stackoverflow.com/questions/72800045/save-several-data-frames-with-different-names-with-loop, still can't get what I desired.

Any help would be greatly appreciated.

答案1

得分: 0

请注意,将变量名称转换为字符串并不被视为良好的实践,即使可能可以实现(例如,参考这个线程)。

但这不是您的主要问题:当您定义列表时,您没有为其元素设置名称,因此变量名称被“丢失”(查看您的列表以查看它:names(list))。

最后,您不应该使用函数名称来定义变量。list 是 R 中的一个函数(用于构建...列表):因为您用您的新变量替代它,所以不能再使用该函数。

设置变量名称并在循环中使用它们的良好工作流程可能如下所示:

l = list()

l["df1"] = data.frame(t = c(1,2,3))
l["df2"] = data.frame(t = c(1,2,3))
l["df3"] = data.frame(t = c(1,2,3))

for (i in 1:length(l)){
  write.csv(l[[i]], paste0(names(l)[i], '.csv'), row.names = FALSE)
}

希望这有所帮助。

英文:

Note that it is not regarded as good practice to convert variable names into string, even if it is possible (e.g. this thread).

But this is not your main problem : when you define your list, you do not set name to its elements, so the variable name are "lost" (take a look at your list to see it : names(list)).

Lastly, you shouldn't use a function name to define a variable. list is a function in R (which is used to build... list) : as you're replacing it with you're new variable, you cannot use anymore the function.

A good workflow for setting name variables and using them in a loop would look like something like this :

l = list()

l[&quot;df1&quot;] = data.frame(t = c(1,2,3))
l[&quot;df2&quot;] = data.frame(t = c(1,2,3))
l[&quot;df3&quot;] = data.frame(t = c(1,2,3))

for (i in 1:length(l)){
  write.csv(l[[i]], paste0(names(l)[i], &#39;.csv&#39;), row.names = FALSE)
}

Hope this helps

huangapple
  • 本文由 发表于 2023年6月15日 14:23:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定