我有以下数据:
library(dplyr)
group_1 <- c(1,1,2,2,1,1,2,2)
group_2 <- c("A","A","A","A","B","B","B","B")
val <- c(sample(8))
xyz <- c(sample(8))
abc <- c(sample(8))
def <- c(sample(8))
ab23 <- c(sample(8))
df <- data.frame(group_1,group_2,val,xyz,abc,def,ab23)
df <- df %>% group_by(group_1,group_2) %>%
mutate(val_per = val/sum(val,na.rm = TRUE),
xyz_per = xyz/sum(xyz,na.rm = TRUE),
abc_per = abc/sum(abc,na.rm = TRUE),
def_per = def/sum(def,na.rm = TRUE),
ab23_per = ab23/sum(ab23,na.rm = TRUE))
我不想改变新列来为每列创建百分比。有没有办法创建新列,其中每列都有百分比。
你可以这样做across
-
library(dplyr)
df %>%
group_by(group_1,group_2) %>%
mutate(across(.fns = prop.table, .names = '{col}_per')) %>%
ungroup
# group_1 group_2 val xyz abc def ab23 val_per xyz_per abc_per
# <dbl> <chr> <int> <int> <int> <int> <int> <dbl> <dbl> <dbl>
#1 1 A 4 5 2 3 1 0.667 0.714 0.222
#2 1 A 2 2 7 6 3 0.333 0.286 0.778
#3 2 A 8 4 3 7 7 0.889 0.364 0.429
#4 2 A 1 7 4 1 5 0.111 0.636 0.571
#5 1 B 5 6 5 2 8 0.455 0.857 0.455
#6 1 B 6 1 6 5 6 0.545 0.143 0.545
#7 2 B 7 8 8 4 2 0.7 0.727 0.889
#8 2 B 3 3 1 8 4 0.3 0.273 0.111
# … with 2 more variables: def_per <dbl>, ab23_per <dbl>
prop.table(x)
与 相同x/sum(x)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句