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


我想添加属于同一类的每个单元格(第一个表中的行- Person1类型B和列B_1单元格将与第二个表中的行- Person1类型B和列B_1单元格相加,依此类推)
最终的表格将是这样的。请注意,D不在第一个表中,因此它将按原样存在。

我想将所有的偶联表汇总(汇集)到一个包含所有可用属性的表中。如何在R中实现这一点?
谢谢
发布于 2021-05-18 22:05:48
由于您没有提供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)

https://stackoverflow.com/questions/67586651
复制相似问题