我有以下数据:
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))我不想为了为每一列创建百分比而改变新的列。有没有一种方法来创建具有每一列百分比的新列。
发布于 2021-06-29 00:54:00
使用proportions
library(dplyr)
df %>%
group_by(across(starts_with('group'))) %>%
mutate(across(everything(), proportions, .names = "{col}_per")) %>%
ungroup-ouptut
# A tibble: 8 x 12
group_1 group_2 val xyz abc def ab23 val_per xyz_per abc_per def_per ab23_per
<dbl> <chr> <int> <int> <int> <int> <int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 A 2 2 3 2 7 0.286 0.2 0.273 0.286 0.7
2 1 A 5 8 8 5 3 0.714 0.8 0.727 0.714 0.3
3 2 A 4 1 2 8 1 0.364 0.2 0.667 0.667 0.333
4 2 A 7 4 1 4 2 0.636 0.8 0.333 0.333 0.667
5 1 B 6 3 5 7 8 0.857 0.3 0.556 0.875 0.571
6 1 B 1 7 4 1 6 0.143 0.7 0.444 0.125 0.429
7 2 B 8 6 7 3 4 0.727 0.545 0.538 0.333 0.444
8 2 B 3 5 6 6 5 0.273 0.455 0.462 0.667 0.556https://stackoverflow.com/questions/68162301
复制相似问题