gpt4 book ai didi

r - 使用 lapply : How to paste object names to file names? 将数据帧列表写入文件

转载 作者:行者123 更新时间:2023-12-04 10:27:30 26 4
gpt4 key购买 nike

我有一个数据框列表:

lists <- replicate(10, as.data.frame(matrix(rnorm(100), 10, 10)), simplify = FALSE)
names(lists) <- LETTERS[1:10]

我想将所有数据帧写入一个单独的文件,根据它们在 R 中的对象名称命名。我试过 lapplypaste ,但这可怕地失败了:
lapply(lists, function(x) write.table(x, file=paste(x,".txt"), sep="\t"))
Error in file(file, ifelse(append, "a", "w")) :
invalid 'description' argument
In addition: Warning message:
In if (file == "") file <- stdout() else if (is.character(file)) { :
the condition has length > 1 and only the first element will be used
Called from: file(file, ifelse(append, "a", "w"))

如何在不为 n 个 data.frames 写 n 个单行的情况下做到这一点?

最佳答案

您正在循环列表元素,而不是列表元素的名称。所以表达式 paste(x,".txt") 试图将 data.frame 粘贴到 .txt ,但您想将列表元素的名称粘贴到 .txt 。因此,您可以尝试以下操作:

lists <- replicate(10, as.data.frame(matrix(rnorm(100), 10, 10)), simplify = FALSE)
names(lists) <- LETTERS[1:10]

lapply(names(lists), function(x) write.table(lists[[x]], file=paste(x,".txt"), sep="\t"))

要抑制控制台输出,请将语句包装在 invisible() 中,或者使用常规 for 循环:
for (x in names(lists))
write.table(lists[[x]], file=paste(x,".txt"), sep="\t")

关于r - 使用 lapply : How to paste object names to file names? 将数据帧列表写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48734176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com