R语言合并行列名称及长度不同的两个数据框的方法求助
问题1 合并传球矩阵和事件计数矩阵
直接对两个数据做全连接即可,代码如下:
library(dplyr) library(tibble) library(tidyr) # 定义dfList dfList <- c("P1", "P2", "P3", "P4", "P5") # 生成goodMatrix(和你的逻辑一致) goodMatrix <- dtMatrix %>% filter(Event == 'Good Pass' & !is.na(Receiver)) %>% dplyr::count(category, Receiver) %>% tidyr::complete(category = dfList, Receiver = dfList, fill = list(n = 0)) %>% pivot_wider(names_from = Receiver, values_from = n) %>% column_to_rownames('category') # 生成事件统计宽表 event_df <- dtMatrix %>% dplyr::count(category, Event) %>% pivot_wider(names_from = Event, values_from = n, values_fill = 0) # 合并两个表 result <- rownames_to_column(goodMatrix, "category") %>% full_join(event_df, by = "category") %>% arrange(factor(category, levels = c(dfList, "Opponent"))) %>% column_to_rownames("category") %>% mutate(across(everything(), ~replace(., is.na(.), 0)))
运行后得到的result和你给出的expectedOutput完全一致。
问题2 合并行列长度不同的两个数据框
你只需要先取两个表行名、列名的并集,初始化目标表后分别填充数据即可,代码如下:
# 取行列并集 all_rows <- union(rownames(passesComb), rownames(copyComb)) all_cols <- union(colnames(passesComb), colnames(copyComb)) # 初始化结果表 gamesComb <- data.frame(matrix(NA, nrow = length(all_rows), ncol = length(all_cols), dimnames = list(all_rows, all_cols))) # 填充passesComb的数据 gamesComb[rownames(passesComb), colnames(passesComb)] <- passesComb # 若需要用copyComb的值覆盖重叠位置,取消注释下一行即可 # gamesComb[rownames(copyComb), colnames(copyComb)] <- copyComb # 若需要将空值替换为0,取消注释下一行即可 # gamesComb[is.na(gamesComb)] <- 0
内容的提问来源于stack exchange,提问作者samrizz4
相关产品推荐
相关产品推荐

