【问题标题】:How to sum up all the contingency tables into one? in R如何将所有列联表汇总为一张?在 R 中
【发布时间】:2021-08-07 17:12:08
【问题描述】:

我有许多列联表 (100),在一个 excel 文件中收集了许多工作表。其中一些具有比其他更多的属性。但最后它们都有相同的列和行名称。 (更多或更少的属性)。 例如,假设我们有这 2 个表。

我想添加属于同一类的每个单元格(第一个表中的行 - Person1 类型 B 和列 B_1 单元格将与行 - 第二个表中的 Person1 类型 B 和列 B_1 单元格相加,依此类推)

决赛桌会是这样。注意 D 不在第一个表中,所以它将按原样存在。

我想将所有列联表汇总(池化)为一个具有所有可用属性的表。如何在 R 中实现这一点?

谢谢

【问题讨论】:

  • 请提供您的预期输出。并通过dput() 提供您的输入数据,而不是图像。
  • 同意@Limey。此外,一个示例 excel 文件将有助于回答...
  • @Limey 我已经添加了更多解释。谢谢!
  • @Wimpel 我从 excel 文件中得到了这个。我举个例子吧。

标签: r sum contingency


【解决方案1】:

由于您没有提供 excel 文件,我根据您提供的图像制作了一个文件..

看起来像这样

library(tidyverse)
library(tidyxl)
library(readxl)
library(data.table)
library(unpivotr)

file_to_read <- "./testdata.xlsx"
# Get all names of sheets in the file
sheet_names <- readxl::excel_sheets(file_to_read)
# Loop through sheets
L <- lapply(sheet_names, function(x) {
  all_cells <-
    tidyxl::xlsx_cells(file_to_read, sheets = x) %>%
    dplyr::select(sheet, row, col, data_type, character, numeric)
  # Cells with the actual data  
  cells_data <-
    dplyr::filter(all_cells, row >= 3, col >= 3) %>%
    dplyr::transmute(row, col, sheet = sheet, value = numeric)
  # Select the headers
  person.number.up <-
    dplyr::filter(all_cells, row == 1) %>%
    dplyr::select(row, col, person.number.up = character)
  person.type.up <- 
    dplyr::filter(all_cells, row == 2) %>%
    dplyr::select(row, col, person.type.up = character)
  person.number.left <-
    dplyr::filter(all_cells, col == 1) %>%
    dplyr::select(row, col, person.number.left = character)
  person.type.left <- 
    dplyr::filter(all_cells, col == 2) %>%
    dplyr::select(row, col, person.type.left = character)
  #put together
  final.df <- cells_data %>%
    unpivotr::enhead(person.number.up, "up-ish") %>%
    unpivotr::enhead(person.type.up, "up-ish") %>%
    unpivotr::enhead(person.number.left, "left-ish") %>%
    unpivotr::enhead(person.type.left, "left-ish") %>%
    dplyr::select(-(1:2))
})
# Put together in a data.table
DT <- data.table::rbindlist(L, use.names = TRUE)
# Cast to wide, summing values in the process
ans <- dcast(DT, person.number.left + person.type.left ~ person.number.up + person.type.up, 
      value.var = "value", 
      fun.aggregate = sum, na.rm = TRUE)

【讨论】:

  • 注意:您可能需要unpivotr::justify() 将标头设置为数据的左上角以避免联系...请参阅unpivotr::direction() 下的-ish-section
  • 这条线是干什么用的? # 具有实际数据的单元格 cells_data = 3, col >= 3) %>% dplyr::transmute(row, col, sheet = sheet, value = numeric)
  • 感谢您的预处理步骤。我为每个表手动添加了标题以引用特定的人(就像您所做的一样,但手动获得更准确的结果。我喜欢五种类型,每个表都不同)。然后,我将本节中的数字(# Select the headers)更改为该列中的名称。例如(person.number.up % dplyr::select(row, col, person.number.up = character))。我收到此错误,(错误:无法对不存在的列进行子集化。x 列 row 不存在)
  • 我用我拥有的数据更新了问题。
  • 现在你问的是一个完全不同的问题。最好开始一个新的。并使其可重现(参见常见问题解答)。如果您只发布数据图像,您将无法获得最佳/最快的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
相关资源
最近更新 更多