我想计算 Dataframe 中每一列的百分比并为每一列创建一个自定义名称。
考虑以下代码:
a<-structure(list(year = 2000:2005, Col1 = 1:6, Col2 = c(1L, 4L,
9L, 16L, 25L, 36L)), row.names = c(NA, -6L), class = "data.frame")
> a
year Col1 Col2
1 2000 1 1
2 2001 2 4
3 2002 3 9
4 2003 4 16
5 2004 5 25
6 2005 6 36
a<-a %>% rowwise() %>%
mutate(total = sum(across(starts_with("Col")), na.rm = T)) %>% data.frame()
a %>%
mutate_at(vars(starts_with("Col")) , funs(P = ./a$total * 100))
输出如下:
如何处理最后两列的名称(例如 per_Col1 和 per_Col2 而不是 Col1_P 和 Col2_P,主要问题)?有没有更好的方法(使用 dplyr 包)来做到这一点?(而不是计算列的总和然后将每一列除以它)
最佳答案
您可以将 across 与 .names 参数一起使用:
a %>%
rowwise() %>%
mutate(total = sum(across(starts_with("Col")), na.rm = TRUE)) %>%
mutate(across(starts_with("Col") , ~./total * 100, .names = 'per_{col}')) %>%
ungroup()
给出:
# A tibble: 6 x 6
year Col1 Col2 total per_Col1 per_Col2
<int> <int> <int> <int> <dbl> <dbl>
1 2000 1 1 2 50 50
2 2001 2 4 6 33.3 66.7
3 2002 3 9 12 25 75
4 2003 4 16 20 20 80
5 2004 5 25 30 16.7 83.3
6 2005 6 36 42 14.3 85.7
关于r - dplyr 如何使用自定义名称计算多列和输出列的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69235661/