如何用dplyr将数据集的b、c、d百分比变量转为绝对数值(不修改原数据)
Convert Percentage Columns to Absolute Values (No Original Data Modification)
Hey there, glad you've resolved this issue already! For others facing the same scenario—needing to turn percentage columns into absolute values without altering your original dataset (and avoiding mutate()), here are reliable approaches:
Using dplyr (No mutate())
Instead of mutate(), use transmute() to create an entirely new dataset. This function builds a new data frame with the columns you specify, leaving your original data untouched.
library(dplyr) # Replace 'original_df' with your actual dataset name converted_df <- original_df %>% transmute( key = key, # Retain the original total column b_absolute = key * b / 100, c_absolute = key * c / 100, d_absolute = key * d / 100 )
Base R Alternative
If you prefer sticking to base R, you can directly construct a new data frame:
converted_df <- data.frame( key = original_df$key, b_absolute = original_df$key * original_df$b / 100, c_absolute = original_df$key * original_df$c / 100, d_absolute = original_df$key * original_df$d / 100 )
Both methods ensure your original dataset stays exactly as it was, while giving you the absolute values you need in a separate data frame.
内容的提问来源于stack exchange,提问作者S. Ahmad
相关产品推荐
相关产品推荐

