英文:
Calculate percentage depending on a certain column
问题
以下是您要求的代码的翻译部分:
我想知道每一行如何根据列计算百分比?
这是一个虚拟数据集:
c <- c(10, 20, 30, 40, 50)
b <- c(40, 2, 40, 10, 50)
a <- c(100, 50, 70, 60, 100)
id <- c("a", "b", "c", "d", "e")
data <- data.frame(id, a, b, c)
head(data)
# id a b c
# 1 a 100 40 10
# 2 b 50 2 20
# 3 c 70 40 30
# 4 d 60 10 40
# 5 e 100 50 50
对于每一行,我们如何设置列 "a" 为 100% 并根据它来计算列 "b" 和 "c" 的比例?
以下是预期的输出:
# id a b c proportion_b proportion_c
# 1 a 100 40 10 40 10
# 2 b 50 2 20 4 40
# 3 c 70 40 30 57.14286 42.85714
# 4 d 60 10 40 16.66667 66.66667
# 5 e 100 50 50 50 50
如果可能的话,更喜欢使用 `tidyverse` 方法。谢谢。
英文:
I would like to know for each row how to calculate percentage depends on the column?
Here is dummy datasets:
c <- c(10, 20, 30, 40, 50)
b <- c(40, 2, 40, 10, 50)
a <- c(100, 50, 70, 60, 100)
id <- c("a", "b", "c", "d", "e")
data <- data.frame(id, a, b, c)
head(data)
# id a b c
# 1 a 100 40 10
# 2 b 50 2 20
# 3 c 70 40 30
# 4 d 60 10 40
# 5 e 100 50 50
For each row how do we set column "a" is a 100% and depends on that calculate proportion for the column b and c?
Here is the expected output:
# id a b c proportion_b proportion_c
# 1 a 100 40 10 40 10
# 2 b 50 2 20 4 40
# 3 c 70 40 30 57.14286 42.85714
# 4 d 60 10 40 16.66667 66.66667
# 5 e 100 50 50 50 50
If its possible tidyverse
approach more preferred. Thank you.
答案1
得分: 11
Using base R
nm1 <- c("b", "c")
data[paste0("proportion_", nm1)] <- data[nm1] / data$a * 100
-output
> data
id a b c proportion_b proportion_c
1 a 100 40 10 40.00000 10.00000
2 b 50 2 20 4.00000 40.00000
3 c 70 40 30 57.14286 42.85714
4 d 60 10 40 16.66667 66.66667
5 e 100 50 50 50.00000 50.00000
英文:
Using base R
nm1 <- c("b", "c")
data[paste0("proportion_", nm1)] <- data[nm1]/data$a * 100
-output
> data
id a b c proportion_b proportion_c
1 a 100 40 10 40.00000 10.00000
2 b 50 2 20 4.00000 40.00000
3 c 70 40 30 57.14286 42.85714
4 d 60 10 40 16.66667 66.66667
5 e 100 50 50 50.00000 50.00000
</details>
# 答案2
**得分**: 7
```r
library(dplyr)
data %>%
mutate(across(b:c, ~ .x / a * 100, .names = "proportion_{.col}"))
# id a b c proportion_b proportion_c
# 1 a 100 40 10 40.00000 10.00000
# 2 b 50 2 20 4.00000 40.00000
# 3 c 70 40 30 57.14286 42.85714
# 4 d 60 10 40 16.66667 66.66667
# 5 e 100 50 50 50.00000 50.00000
英文:
You can divide a
into b
and c
at the same time with across()
:
library(dplyr)
data %>%
mutate(across(b:c, ~ .x / a * 100, .names = "proportion_{.col}"))
# id a b c proportion_b proportion_c
# 1 a 100 40 10 40.00000 10.00000
# 2 b 50 2 20 4.00000 40.00000
# 3 c 70 40 30 57.14286 42.85714
# 4 d 60 10 40 16.66667 66.66667
# 5 e 100 50 50 50.00000 50.00000
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论