SiH
SiH

Reputation: 1546

how can I use mutate in dplyr to modify variable dynamically?

I wish to dynamically select variables and modify them in tibble dataframe. I have copied a sample problem. Can someone please help with that. Thanks

df <- tibble(
x = c(1, 2, 3),
y = c(4, 5, 6),
z = c(6, 7, 8))

variables = c("x", "y")

for (var in variables)
{
   df <- df %>% mutate(var = var + 1)
}

Upvotes: 1

Views: 182

Answers (2)

akrun
akrun

Reputation: 887138

We can use mutate with across

library(dplyr)
df %>% 
   mutate(across(all_of(variables), ~ . + 1))

-output

# A tibble: 3 x 3
#      x     y     z
#  <dbl> <dbl> <dbl>
#1     2     5     6
#2     3     6     7
#3     4     7     8

data

df <- tibble(
  x = c(1, 2, 3),
  y = c(4, 5, 6),
  z = c(6, 7, 8))
variables = c("x", "y")

Upvotes: 2

Duck
Duck

Reputation: 39595

Try this. You can use !! from rlang and sym() from dplyr to make the evaluation you want using the operator :=. Here the code:

library(dplyr)
#Data and code
df <- tibble(
  x = c(1, 2, 3),
  y = c(4, 5, 6),
  z = c(6, 7, 8))

variables = c("x", "y")

for (var in variables)
{
  var <- sym(var)
  df <- df %>% mutate(!!var := !!var + 1)
}

Output:

# A tibble: 3 x 3
      x     y     z
  <dbl> <dbl> <dbl>
1     2     5     6
2     3     6     7
3     4     7     8

Upvotes: 1

Related Questions