我有以下数据:
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-28 19:24:31
你可以用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)相同。
发布于 2021-06-28 20:34:01
我们也可以这样做:
library(dplyr)
library(purrr)
df %>%
bind_cols(df %>%
select(!starts_with("group")) %>%
map_dfc(~ .x / sum(.x)) %>%
set_names(paste(names(.), "_per", sep = "")))
group_1 group_2 val xyz abc def ab23 val_per xyz_per abc_per def_per ab23_per
1 1 A 3 4 1 4 5 0.08333333 0.11111111 0.02777778 0.11111111 0.13888889
2 1 A 2 2 6 8 2 0.05555556 0.05555556 0.16666667 0.22222222 0.05555556
3 2 A 8 8 7 3 3 0.22222222 0.22222222 0.19444444 0.08333333 0.08333333
4 2 A 5 7 8 5 6 0.13888889 0.19444444 0.22222222 0.13888889 0.16666667
5 1 B 6 5 4 2 4 0.16666667 0.13888889 0.11111111 0.05555556 0.11111111
6 1 B 4 1 5 7 8 0.11111111 0.02777778 0.13888889 0.19444444 0.22222222
7 2 B 7 6 2 6 7 0.19444444 0.16666667 0.05555556 0.16666667 0.19444444
8 2 B 1 3 3 1 1 0.02777778 0.08333333 0.08333333 0.02777778 0.02777778发布于 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
复制相似问题