繁体   English   中英

dplyr :: mutate_at使用多个功能

[英]dplyr::mutate_at using multiple functions

我可以在单个mutate_at步骤中在同一列上连续使用多个函数吗,例如:(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

我尝试时得到了这个

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

抱歉,如果这是重复的q,请尝试搜索

您可以,但是您需要这样做:

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

如果要保留原始列,请使用@phiver公式:

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

您总是可以只构建自己的函数并在funs()运行它。

require(tidyverse)     
myFunc <- function(x) {log(sqrt(x))}

head(mtcars) %>% 
select(mpg, disp) %>% 
mutate_at(vars(mpg,disp), funs(myFunc))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM