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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With