0

I'm trying to to apply mutate over multiple columns.

My dataframe contains 10 columns that are named:

Anne
Carol
Jane
Sophanie
Gordon
Donald
Jeffrey
Adam
Sophie
Smith

Until now I've done the following to select the columns one by one:

dataframe$Anne
dataframe$Carol

And so forth.

Now I want to use a mutate function so I can select all these 10 names in a single pipe/command. How do I do that?

Andrea M
  • 2,314
  • 1
  • 9
  • 27
Henry Oufh
  • 135
  • 1
  • 1
  • 8

2 Answers2

0

With across()

library(tidyverse)

tibble(
  Anne = 1:10, 
  Carol = 1:10, 
  Jane = 1:10
) %>%  
  mutate(across(Anne:Jane, ~ .x * 2))

# A tibble: 10 x 3
    Anne Carol  Jane
   <dbl> <dbl> <dbl>
 1     2     2     2
 2     4     4     4
 3     6     6     6
 4     8     8     8
 5    10    10    10
 6    12    12    12
 7    14    14    14
 8    16    16    16
 9    18    18    18
10    20    20    20
Chamkrai
  • 5,912
  • 1
  • 4
  • 14
0

Let's first create a minimal, reproducible example:

dat <- data.frame(Anne = c(1, 2),
                  Carol = c(3, 4),
                  Jane = c(5, 6))

dat
#>   Anne Carol Jane
#> 1    1     3    5
#> 2    2     4    6

library(dplyr)

across() lets you apply a dplyr function to more than one column. In the simplest case, you can apply it to all columns - everything().

Imagine you want to replace all values with 0:

dat |> mutate(across(everything(), ~ 0))
#>   Anne Carol Jane
#> 1    0     0    0
#> 2    0     0    0

Most of the times you want to do something more complex, like applying an if_else call to multiple columns:

dat |> mutate(across(everything(), ~ if_else(.x <= 3, "small", "big")))
#>    Anne Carol Jane
#> 1 small small  big
#> 2 small   big  big

Created on 2022-08-21 by the reprex package (v2.0.1)

Andrea M
  • 2,314
  • 1
  • 9
  • 27