Home > other >  Put multiple functions into a single dplyr mutate across everything e.g. change mulitple different s
Put multiple functions into a single dplyr mutate across everything e.g. change mulitple different s

Time:10-26

Example data:

df1 = data.frame(x1 = rep(c("foo", "bar"), 4),
                 x2 = rep(c("FOO", "fix", "broke", "fix"), 2))

I want to, for example, change multiple different strings, in this case change foo to done and bar to open. I am using stringr and dplyr. Is it possible to put more than one function after the ~ so that multiple functions are run across all columns in the same line of code, rather than as the example above where across and everything are repeated:

> df1%>%
    mutate(across(everything(), ~ str_replace(.,"(?i)bar", "open")),
           across(everything(), ~ str_replace(., "(?i)foo", "done")))
    x1    x2
1 done  done
2 open   fix
3 done broke
4 open   fix
5 done  done
6 open   fix
7 done broke
8 open   fix

CodePudding user response:

I guess the tidyverse way would be to chain multiple functions together using the pipe operator. This means you only need to call across once.

df1 %>% 
   mutate(across(everything(), ~ str_replace(.,"(?i)bar", "open") %>% 
                                 str_replace("(?i)foo", "done")))
    x1    x2
1 done  done
2 open   fix
3 done broke
4 open   fix
5 done  done
6 open   fix
7 done broke
8 open   fix

CodePudding user response:

Alternatively, you may also use str_replace_all -

library(dplyr)
library(stringr)

df1 %> 
    mutate(across(.fns = ~str_replace_all(., c("(?i)bar" = "open", "(?i)foo" = "done"))))

#    x1    x2
#1 done  done
#2 open   fix
#3 done broke
#4 open   fix
#5 done  done
#6 open   fix
#7 done broke
#8 open   fix
  • Related