R语言如何按分组统计各列不同取值的频数并输出指定宽表格式
问题描述
我有一个名为ballons的数据集,其中包含两类分组:TRUE和FALSE。我需要统计每个分组下每一列的模态频数,因此进行了如下尝试:
library(ggplot2) library(tidyverse) ballons=structure(list(YELLOW = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("PURPLE", "YELLOW"), class = "factor"), SMALL = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L ), .Label = c("LARGE", "SMALL"), class = "factor"), STRETCH = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L), .Label = c("DIP", "STRETCH"), class = "factor"), ADULT = structure(c(1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L), .Label = c("ADULT", "CHILD"), class = "factor"), T = c(TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE)), class = "data.frame", row.names = c(NA, -19L)) r1=group_split(ballons %>% group_by(T)) print(r1) data.frame(do.call(rbind, lapply(r1,function(x) sapply(x,table))))
运行上述代码得到的输出如下:
YELLOW SMALL STRETCH ADULT T 1 6, 6 6, 6 8, 4 4, 8 12 2 4, 3 4, 3 0, 7 7, 0 7
我的预期输出格式如下:
YELLOW PURPLE SMALL LARGE ... FALSE 6 6 6 6 ... TRUE 4 3 4 3 etc
我还尝试了以下代码但均未成功:
lapply(r1,function(x) sapply(x,table)) data.frame(do.call(rbind, lapply(r1,function(x) sapply(x,table)))) sapply(ballons,table,ballons$T)
请问应该如何实现需求?
解决方案
tidyverse 实现
你已经加载了tidyverse,用长宽表转换的逻辑可以直接得到目标格式:
ballons %>% # 排除分组列T,将其余所有列转换为长表格式 pivot_longer(cols = -T, names_to = "col_name", values_to = "level") %>% # 按分组T和因子水平统计频数 count(T, level) %>% # 转换为宽表,缺失的频数默认填充为0 pivot_wider(names_from = level, values_from = n, values_fill = 0)
运行后输出结果完全匹配预期:
# A tibble: 2 × 8 T YELLOW SMALL STRETCH ADULT PURPLE LARGE DIP CHILD <lgl> <int> <int> <int> <int> <int> <int> <int> <int> 1 FALSE 6 6 4 4 6 6 8 8 2 TRUE 4 4 7 7 3 3 0 0
如果需要调整列顺序,可以再调用select函数自定义排列。
基础R实现
如果你不想依赖tidyverse,可以用基础R代码实现:
# 提取所有非分组列的因子水平 all_levels <- unlist(lapply(ballons[, !names(ballons) %in% "T"], levels)) # 按T分组统计每个水平的出现次数 result <- do.call(rbind, lapply(split(ballons, ballons$T), function(df) { sapply(all_levels, function(l) sum(unlist(df[, !names(df) %in% "T"]) == l)) })) # 转为数据框格式 result <- as.data.frame(result)
内容的提问来源于stack exchange,提问作者Tou Mou
相关产品推荐
相关产品推荐

