【问题标题】:How to create one excel workbook with multiple sheets in it where each sheet is a data frame如何创建一个包含多个工作表的 Excel 工作簿,其中每个工作表都是一个数据框
【发布时间】:2015-08-07 10:52:41
【问题描述】:

我必须针对 1 个变量(a)计算 50 个变量(分类)的总和 发现后,我想在一个 Excel 工作簿中创建 50 张工作表,其中每张工作表如下所示:- “变量名”a 1 10 2 21 3 18 . .

等等。

我可以创建 50 个 csv,然后将它们合并到 1 个工作簿中,但这是一个漫长的过程。 我想要的是获得一个循环运行的函数,将计算聚合然后写在工作簿的工作表中;对所有 50 次执行此操作(变量)

package:- WriteXLS 是我用的。

【问题讨论】:

标签: r excel


【解决方案1】:

这是一个涉及两个步骤的解决方案:1) 将每个变量的汇总统计信息作为列表中的单独数据框获取,然后 2) 将该列表的元素作为单独的工作表写入 Excel 工作簿中。我使用iris 作为测试平台并使用xlsx 而不是WriteXLS,因为它使附加工作表更容易。

library(dplyr)
library(lazyeval)
library(xlsx)

# Start with a function to get your summary stats by id
aggregateit <- function(x) {
    require(dplyr)
    require(lazyeval)
    result <- iris %>%  # need to name your initial df here
        group_by(Species) %>%  # need to name your id var here
        summarise_(mean = interp(~mean(var), var = as.name(x)))  # See http://stackoverflow.com/questions/26724124/standard-evaluation-in-dplyr-summarise-on-variable-given-as-a-character-string
    return(result)
}

# Now apply that function to all desired variables --- here, all non-id columns in iris,
# which are columns 1 through 4 --- and then assign the variables names to the elements
# of that list.
agglist <- lapply(names(iris)[1:4], aggregateit)
names(agglist) <- names(iris)[1:4]

# Now write the data frames in that list to a workbook with nice names for the sheets
for (i in 1:length(agglist)) write.xlsx(agglist[[i]], file="filename.xlsx",
    sheetName=names(agglist)[i], append=TRUE)

这是一个在初始函数中使用aggregate 的版本,因此您可以根据需要在基础 R 中完成所有操作:

aggregateit <- function(variable) {
    var.mean <- aggregate(variable ~ Species, iris, FUN=function(x) mean(x))  # need to swap in your df and id var names
    var.sd <- aggregate(variable ~ Species, iris, FUN=function(x) sd(x)) # ditto
    result <- merge(var.mean, var.sd, by = "Species")  # again for id var
    names(result) <- c("Species", "mean", "sd")  # once more
    return(result)
}

agglist <- lapply(iris[,1:4], aggregateit)

for (i in 1:length(agglist)) write.xlsx(agglist[[i]], file="iris.sumstats.xlsx",
    sheetName=names(agglist)[i], append=TRUE, row.names = FALSE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 2022-12-24
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    相关资源
    最近更新 更多