gpt4 book ai didi

r - 如何将数据框的名称传递给 Excel 工作表(使用 xlsx 包)

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

我正在尝试使用 lapply 遍历数据帧列表并对每个数据帧执行自定义函数。在函数中,我试图根据数据集的名称命名工作表(使用 xlsx)。这可能吗?参见示例:

myList <- list(DataFrame1, DataFrame2, DataFrame3, DataFrame4)

require(xlsx)
export <- createWorkbook()

lapply(myList,
ExcelExport <- function(dataset) {

nameDF <- deparse(substitute(dataset))

# Use another function and store the output
DF <- as.data.frame(function2(dataset))
# Here is where I'm having trouble naming the worksheet according to the name of the Dataframe:
wksht <- createSheet(wb=export, sheetName = paste("Dataset is ", nameDF, sep = ""))
addDataFrame(x=DF, sheet = wksht)


)
# Save it to an excel file (either existing or new) under a given name
saveWorkbook(export, "Export1.xlsx")

我从 Getting the name of a data frame 中找到了 deparse(substitute())但 lapply 似乎将我的数据框重命名为 X[[i]],然后抛出 '[' 的无效字符错误

最佳答案

这里是经过编辑的代码,允许您访问列表节点的名称。请在发布前检查您的代码,它包含一些歧义。

myList <- list(DataFrame1 = data.frame(matrix(rnorm(100), 10, 10)), 
DataFrame2 = data.frame(matrix(rnorm(100), 10, 10)),
DataFrame3 = data.frame(matrix(rnorm(100), 10, 10)),
DataFrame4 = data.frame(matrix(rnorm(100), 10, 10)))

require(xlsx)
export <- createWorkbook()

lapply(seq_along(myList), function(i) {
ExcelExport <- function1(myList[[i]]) # Your code was incomplete here
# You don't have object 'ExcelExport' anywhere esle in your code
# so this step seems useless...

# Now you have a full access to myList inside lapply
nameDF <- names(myList)[i]

# Use another function and store the output
DF <- as.data.frame(function2(myList[[i]]))

wksht <- createSheet(wb=export, sheetName = paste("Dataset is ", nameDF, sep = ""))
addDataFrame(x=DF, sheet = wksht) # Btw, object 'wksht' is not defined in your code

})
# Save it to an excel file (either existing or new) under a given name
saveWorkbook(export, "Export1.xlsx")

关于r - 如何将数据框的名称传递给 Excel 工作表(使用 xlsx 包),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30203943/

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