user3245256
user3245256

Reputation: 1948

dplyr mutate_at function applied to multiple columns - using dynamic column names

I have a data frame x.

x <- data.frame(a = c(10, 20, 30, 0), b = c(1, 2, 3, 0), c = c(1, 2, 3, 0), d = c(8, 16, 24, 0))
x
denominator_var <- "a"
numerator_vars <- c("b", "c", "d")

Using dplyr, I'm trying to add new columns (b_share, c_share, and d_share) such that each of them are equal to the corresponding column (b, c, and d) divided into a. However, it is important to me to use NOT the original variable names but dynamic variable names.

My code below is not working. What's wrong?

x %>% mutate_at(vars(one_of(numerator_vars)),
                funs(share = ifelse(!!(denominator_var) > 0, round(./!!(denominator_var) * 100, 2), 0)))

Thank you very much!

Upvotes: 2

Views: 1548

Answers (2)

C. Braun
C. Braun

Reputation: 5201

You can get the result you want by quoting your denominator beforehand:

denominator_var <- quo(a)
x %>% mutate_at(numerator_vars,
                funs(share = ifelse(!!(denominator_var) > 0, 
                                    round(./!!(denominator_var) * 100, 2),
                                    0)))

Also note that you don't need to use vars for your vector numerator_vars.

Upvotes: 1

MKR
MKR

Reputation: 20095

You can try using as.name before applying !!:

x %>% mutate_at(vars(one_of(numerator_vars)), funs(share = 
  ifelse(!!(as.name(denominator_var)), round(./!!(as.name(denominator_var))) * 100, 2)))

#    a b c  d b_share c_share d_share
# 1 10 1 1  8       0       0     100
# 2 20 2 2 16       0       0     100
# 3 30 3 3 24       0       0     100
# 4  0 0 0  0       2       2       2

Upvotes: 1

Related Questions