Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr::mutate_at using multiple functions

Tags:

r

dplyr

Can I use multiple functions in succession on the same column in a single mutate_at step, eg: (sqrt(log(x)))


library(dplyr)

  head(mtcars) %>% 
  select(mpg, disp) %>% 
  mutate_at(vars(mpg,disp)
            , funs(sqrt)) %>% 
  mutate_at(vars(mpg,disp)
            , funs(log))
#>        mpg     disp
#> 1 1.522261 2.537587
#> 2 1.522261 2.537587
#> 3 1.563380 2.341066
#> 4 1.531695 2.776480
#> 5 1.464262 2.943052
#> 6 1.447956 2.708050

I get this when trying

head(mtcars) %>% 
  select(mpg, disp) %>% 
  mutate_at(vars(mpg,disp)
            , funs(sqrt,log))
#>    mpg disp mpg_sqrt disp_sqrt  mpg_log disp_log
#> 1 21.0  160 4.582576  12.64911 3.044522 5.075174
#> 2 21.0  160 4.582576  12.64911 3.044522 5.075174
#> 3 22.8  108 4.774935  10.39230 3.126761 4.682131
#> 4 21.4  258 4.626013  16.06238 3.063391 5.552960
#> 5 18.7  360 4.324350  18.97367 2.928524 5.886104
#> 6 18.1  225 4.254409  15.00000 2.895912 5.416100

Apologies if this is a duplicate q, tried searching

like image 744
Grizzly2501 Avatar asked Mar 06 '23 05:03

Grizzly2501


2 Answers

You can but you need to do it like this:

library(dplyr)

head(mtcars) %>% 
  select(mpg, disp) %>% 
  mutate_at(vars(mpg,disp)
            , funs(log(sqrt(.))))

       mpg     disp
1 1.522261 2.537587
2 1.522261 2.537587
3 1.563380 2.341066
4 1.531695 2.776480
5 1.464262 2.943052
6 1.447956 2.708050
like image 187
phiver Avatar answered Mar 16 '23 12:03

phiver


Here if you want to keep the original columns, using @phiver formula:

head(mtcars) %>% 
 select(mpg, disp) %>% 
    dplyr::mutate_at(.vars=c("mpg","disp")
        ,.funs=funs(logsqrt = log(sqrt(.)))) 

   mpg disp mpg_logsqrt disp_logsqrt
1 21.0  160    1.522261     2.537587
2 21.0  160    1.522261     2.537587
3 22.8  108    1.563380     2.341066
4 21.4  258    1.531695     2.776480
5 18.7  360    1.464262     2.943052
6 18.1  225    1.447956     2.708050
like image 26
A. Suliman Avatar answered Mar 16 '23 12:03

A. Suliman