Home > Net >  Using a function in .names argument of across function
Using a function in .names argument of across function

Time:10-22

In this example dataset I would like to be able to manipulate the .names argument in the second mutate(across... part:

In particluar I would like to manipulate {.col} with a function like sub.

In essence: I would like to remove the greater4 string in the last two columns:

Sepal.Length_greater4_greater50 and Sepal.Width_greater4_greater50 to

Sepal.Length_greater50 and Sepal.Width_greater50

Example data:

library(dplyr)
head(iris, 5) %>% 
  select(1,2) %>% 
  mutate(across(contains("Sepal"), ~ifelse(. > 4, 1, 0), .names = "{.col}_greater4")) %>% 
  mutate(across(contains("4"), ~ifelse(. < 50, 1, 0), .names = "{.col}_greater50"))

Sepal.Length Sepal.Width Sepal.Length_greater4 Sepal.Width_greater4 Sepal.Length_greater4_greater50 Sepal.Width_greater4_greater50
1          5.1         3.5                     1                    0                               1                              1
2          4.9         3.0                     1                    0                               1                              1
3          4.7         3.2                     1                    0                               1                              1
4          4.6         3.1                     1                    0                               1                              1
5          5.0         3.6                     1                    0                               1                              1

CodePudding user response:

Use str_replace within the {}

library(stringr)
library(dplyr)
 head(iris, 5) %>% 
  select(1,2) %>% 
  mutate(across(contains("Sepal"), ~ifelse(. > 4, 1, 0), 
      .names = "{.col}_greater4")) %>% 
  mutate(across(contains("4"), ~ifelse(. < 50, 1, 0), 
    .names = "{str_replace(.col, '_greater4', '_greater50')}"))

-output

  Sepal.Length Sepal.Width Sepal.Length_greater4 Sepal.Width_greater4 Sepal.Length_greater50 Sepal.Width_greater50
1          5.1         3.5                     1                    0                      1                     1
2          4.9         3.0                     1                    0                      1                     1
3          4.7         3.2                     1                    0                      1                     1
4          4.6         3.1                     1                    0                      1                     1
5          5.0         3.6                     1                    0                      1                     1
  • Related