R语言如何转换宽表为长表并计算ymax/ymin适配环形图绘制需求
R语言生成环形图所需长表数据集的方法
你可以直接使用tidyr包的pivot_longer函数完成宽表转长表,再分组计算ymin和ymax即可,完整可运行代码如下:
# 加载所需包 library(dplyr) library(tidyr) # 你原有的数据生成逻辑 position <- c("A", "A", "B", "C", "D", "E", "F", "F") level <- c("P", "S", "J", "J", "P", "S", "S", "S") car <- c("yes", "no", "no", "no", "no", "yes", "no", "yes") car.data <- data.frame(position, level, car) percent_car <- car.data %>% group_by(position) %>% summarise (car_yes = sum(car == "yes"), car_no = sum(car == "no")) %>% mutate(yes_perc = car_yes/(car_yes + car_no), no_perc = car_no/(car_yes + car_no)) # 转换为目标格式数据集 target_df <- percent_car %>% # 宽表转长表,按下划线拆分列名,拆分出yes/no标识和数值类型 pivot_longer( cols = -position, names_to = c(".value", "yes_no"), names_sep = "_" ) %>% # 重命名为你需要的列名 rename( Position = position, car_yes_no = car, yes_no_perc = perc ) %>% # 按职位分组计算环形图所需的上下边界值 group_by(Position) %>% mutate( ymin = lag(cumsum(yes_no_perc), default = 0), ymax = cumsum(yes_no_perc) ) %>% ungroup() # 查看输出结果 print(target_df, n = 12)
补充说明
如果需要调整yes和no的排列顺序,只需要在计算ymin/ymax前,将yes_no列转为自定义顺序的因子即可,示例:
# 调整为no在前,yes在后的顺序 target_df <- target_df %>% mutate(yes_no = factor(yes_no, levels = c("no", "yes"))) %>% arrange(Position, yes_no) %>% group_by(Position) %>% mutate( ymin = lag(cumsum(yes_no_perc), default = 0), ymax = cumsum(yes_no_perc) ) %>% ungroup()
内容的提问来源于stack exchange,提问作者Besz15
相关产品推荐
相关产品推荐

