如何在R中基于total列计算dataframe各列百分比并新增对应列
在R语言中为DataFrame列添加对应百分比列(基于同行total列)
示例数据集
先构造你提供的示例数据:
df <- data.frame( Var = c("A", "D", "B", "R", "V"), total = c(217, 112, 91, 89, 80), col2 = c(77, 14, 15, 77, 8), col3 = c(62, 47, 39, 7, 53), col4 = c(78, 51, 37, 5, 19) )
需求说明
为col2、col3、col4每一列新增对应的百分比列,放置在原列之后,百分比计算规则为:(列值 / 同行total值) * 100,结果保留两位小数并添加百分号。
解决方案
方法1:使用dplyr包(简洁直观)
如果习惯tidyverse工具链,这种写法更清晰:
library(dplyr) df_final <- df %>% # 计算各列百分比并格式化 mutate( col2_percent = sprintf("%.2f%%", col2 / total * 100), col3_percent = sprintf("%.2f%%", col3 / total * 100), col4_percent = sprintf("%.2f%%", col4 / total * 100) ) %>% # 重新排列列顺序,让百分比列紧跟原列 select(Var, total, col2, col2_percent, col3, col3_percent, col4, col4_percent) # 查看结果 print(df_final)
方法2:Base R原生实现(无需额外安装包)
不想依赖第三方包的话,用Base R也能完成:
# 指定需要处理的列 target_cols <- c("col2", "col3", "col4") # 生成所有百分比列 percent_cols <- lapply(target_cols, function(col) { sprintf("%.2f%%", df[[col]] / df$total * 100) }) names(percent_cols) <- paste0(target_cols, "_percent") # 合并数据并按指定顺序排列列 new_col_order <- c( "Var", "total", as.vector(rbind(target_cols, paste0(target_cols, "_percent"))) ) df_final <- cbind(df, percent_cols)[, new_col_order] # 查看结果 print(df_final)
输出结果
两种方法都会得到你期望的输出:
Var total col2 col2_percent col3 col3_percent col4 col4_percent 1 A 217 77 35.48% 62 28.57% 78 35.94% 2 D 112 14 12.50% 47 41.96% 51 45.54% 3 B 91 15 16.48% 39 42.86% 37 40.66% 4 R 89 77 86.52% 7 7.87% 5 5.62% 5 V 80 8 10.00% 53 66.25% 19 23.75%
内容的提问来源于stack exchange,提问作者Rich
相关产品推荐
相关产品推荐

