【问题标题】:Write multiple describeBy summaries to individual worksheets in an Excel workbook using openxlsx使用 openxlsx 将多个 describeBy 摘要写入 Excel 工作簿中的各个工作表
【发布时间】:2020-11-28 00:29:56
【问题描述】:

我有一个大型数据框,我使用psych 库中的describeBy 以多种方式汇总如下:

library(tidyverse)
library(openxlsx)
library(psych)
.
.
.
 # Describe by Region
  lst1 <- describeBy(df[QUESTIONS], df[REGION_DESCRIPTOR])

  # Describe by Doctor
  lst2 <- describeBy(df[QUESTIONS], df[CARE_DESCRIPTOR])

然后我创建一个新工作簿

  wb = createWorkbook()

并开始尝试将 lst1、lst2、.... 写入其中,每个工作表一个项目:

  addWorksheet(wb, REGION_DESCRIPTOR)
  writeData(wb, REGION_DESCRIPTOR, lst1)

  addWorksheet(wb, CARE_DESCRIPTOR)
  writeData(wb, CARE_DESCRIPTOR, lst2)

很遗憾,我收到一条错误消息:

Error in as.data.frame.default(x, stringsAsFactors = FALSE) : 
  cannot coerce class ‘c("psych", "describeBy")’ to a data.frame

如何使用openxlsx 将每个describeBy 对象写入工作表?我尝试过使用writexl,虽然它有效,但我不满意它将describeBy 生成的每个摘要写入不同的工作表。由于我有近十几个 describeBy,每个都有 3-5 个类别,这很快就会变得笨拙。

提前感谢您的帮助

托马斯·飞利浦

【问题讨论】:

  • 您能否将dput(df) 的输出粘贴到问题中以帮助您!
  • 你可以试试do.call(rbind, describeBy(mtcars[, 'mpg'], mtcars[, 'vs']) )
  • 在尝试编写/保存之前,尝试将数据结构从“psych”和“describeBy”更改为更标准的东西,例如数据框。
  • dput(lst1) 的输出太长,无法打印,但开始和结束是这样的:&gt; dput(lst1) structure(list(ASIA_HIGH_INCOME = structure(list(vars = 1:17, n = c(3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), ..., row.names = c("Q1", "Q2", "Q3", "Q4", "Q5", "Q6", "Q7", "Q8", "Q9", "Q10", "Q11", "Q12", "Q13", "Q14", "Q15", "Q16", "Q17"))), .Dim = 10L, .Dimnames = list( Region = c("ASIA_HIGH_INCOME", "ASIA_MIDDLE_INCOME", ..., "WESTERN_EUROPE")), call = by.data.frame(data = x, INDICES = group, FUN = describe, type = type), class = c("psych", "describeBy"))

标签: r psych openxlsx describe


【解决方案1】:

describeBy 的对象输出是 list。我们可以 rbind 将它们添加到单个矩阵或 data.frame 中,它应该可以工作

do.call(rbind, describeBy(mtcars[, 'mpg'], mtcars[, 'vs']) )

【讨论】:

  • 'do.call(rbind, describeBy(df[QUESTIONS, REGION_DESCRIPTOR], df[QUESTIONS, CARE_DESCRIPTOR])) do.call(rbind, describeBy(df[QUESTIONS, REGION_DESCRIPTOR], df [QUESTIONS, : 第二个参数必须是一个列表`
  • @ThomasPhilips 我展示的示例对我有用。您的示例不可重复测试
  • 您的示例确实有效。每个 describeBy 生成一个列,然后可以与 rbind 粘合在一起。就我而言,我将 describeBy 应用于每个描述符的 17 个问题。
  • @ThomasPhilips 你的意思是多组?
  • 效果很好!感谢磨坊。我从未使用过 do.call,但会继续阅读,再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-04
  • 2013-10-23
相关资源
最近更新 更多