Calculate percentage depending on a certain column
Asked Answered
C

2

5

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.

Consequential answered 15/6, 2023 at 2:53 Comment(0)
A
12

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
Anatolia answered 15/6, 2023 at 3:4 Comment(0)
L
13

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
Lindemann answered 15/6, 2023 at 5:36 Comment(0)
A
12

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
Anatolia answered 15/6, 2023 at 3:4 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.