R语言实现两个列表按1/2/3/4/≥5分组统计计数与对应值求和
R实现指定统计需求的代码
首先加载所需依赖包(如果未安装可先运行install.packages(c("dplyr","tidyr"))安装):
library(dplyr) library(tidyr)
步骤1:导入原始数据
# 导入题目给出的原始列表数据 raw_dat <- list( type1 = c(0,0,0,0,0,2,5,5,5,1,1,3), type2 = c(0,0,0,0,0,1,5,2,3,0,0,1) ) # 转换为数据框方便后续处理 df <- data.frame( t1 = raw_dat$type1, t2 = raw_dat$type2 )
步骤2:为type1的值划分Nb分组
df <- df %>% mutate( Nb = case_when( t1 == 1 ~ "1", t1 == 2 ~ "2", t1 == 3 ~ "3", t1 == 4 ~ "4", t1 >= 5 ~ "5+", TRUE ~ NA_character_ # 数值为0的不需要统计,标记为缺失 ) )
步骤3:分别统计type1和type2的Value值
# 统计type1的分组计数 type1_res <- df %>% filter(!is.na(Nb)) %>% group_by(Nb) %>% summarise(Value = n()) %>% mutate(type = "type1") # 统计type2的分组求和 type2_res <- df %>% filter(!is.na(Nb)) %>% group_by(Nb) %>% summarise(Value = sum(t2)) %>% mutate(type = "type2")
步骤4:合并结果并补全缺失分组
final_res <- bind_rows(type1_res, type2_res) %>% # 调整Nb列的排序规则,避免字符排序导致顺序错乱 mutate(Nb = factor(Nb, levels = c("1", "2", "3", "4", "5+"))) %>% # 补全没有统计值的分组,填充Value为0 complete(Nb, type, fill = list(Value = 0)) %>% # 按要求调整列顺序和行顺序 arrange(type, Nb) %>% select(Nb, type, Value)
运行后打印final_res即可得到题目要求的输出结果。
内容的提问来源于stack exchange,提问作者chippycentra
相关产品推荐
相关产品推荐

