[英]How to pass the name of a data frame to an Excel worksheet (using xlsx package)
I am trying to use lapply to go through a list of dataframes and perform a custom function to each. 我正在尝试使用lapply来浏览数据帧列表并对每个数据帧执行自定义函数。 In the function, I am trying to name a worksheet (using xlsx) according to the name of the dataset.
在函数中,我试图根据数据集的名称命名工作表(使用xlsx)。 Is this possible?
这可能吗? See example:
见例子:
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")
I found deparse(substitute())
from Getting the name of a data frame but the lapply seems to be renaming my dataframe to X[[i]]
, which then throws the error of invalid character for '[' 我从获取数据框的名称中找到了
deparse(substitute())
,但lapply似乎是将我的数据框重命名为X[[i]]
,然后为“[” X[[i]]
抛出无效字符的错误
Here is edited code that allows you to access names of the list nodes. 这是编辑后的代码,允许您访问列表节点的名称。 Please check your code before posting, it contains a few ambiguities.
请在发布前检查您的代码,它包含一些含糊之处。
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.