我尝试使用 将三个数字列转换为基于每列总和的百分比mutate(across(.cols = c(...)))
。我通常对一列执行此操作的方法非常有效:
mutate(`Percentage`= ((`Count`/sum(.$`Count`))*100))
当我将类似的原理应用于多列 mutate 调用,使用.x
或.
代替所有调用的值时,它会将每个值除以自身。我哪里做错了?
# Sample Code
test<-data.frame(fruit=c("Apples","Pears","Bananas"),
`John`=c(1,13,34),
`Jacob`=c(5,9,2))%>%
group_by(`fruit`)%>%
mutate(`Total`=sum(`John`,`Jacob`))
# A tibble: 3 × 4
# Groups: fruit [3]
fruit John Jacob Total
<chr> <dbl> <dbl> <dbl>
1 Apples 1 5 6
2 Pears 13 9 22
3 Bananas 34 2 36
fruiteaten<-test%>%
mutate(across(.cols=c(`John`,
`Jacob`,
`Total`), .fns = ~ ((.x/sum(.x))*100)))
# Output
# A tibble: 3 × 4
# Groups: fruit [3]
fruit John Jacob Total
<chr> <dbl> <dbl> <dbl>
1 Apples 100 100 100
2 Pears 100 100 100
3 Bananas 100 100 100
# Desired Output
fruit John Jacob Total
1 Apples 0.02 0.31 0.09
2 Pears 0.27 0.56 0.34
3 Bananas 0.70 0.12 0.56