mutate two or more columns if case_when is used

前端 未结 2 1875
刺人心
刺人心 2021-01-26 21:15

I am trying to use the case_when function for a bunch of columns y a data.frame.

This case does not return the specified columns in mutate

2条回答
  •  清酒与你
    2021-01-26 22:06

    We could use mutate_at

    library(tidyverse)
    cars %>%
       mutate(km = speed * dist, mt = km/1000) %>%
       mutate_at(vars(km, mt), funs(case_when(speed < 20 ~ .*2,
                                          TRUE ~ .)))
    

    If we need to do computation with separate values for each of the column, then use map2 or pmap

    out <- cars %>%
             mutate(km = speed * dist, mt = km/1000)  %>%  
             select(km, mt) %>%
             map2_df(., list(2, 3), ~ 
               case_when(cars$speed < 20 ~ .x * .y, TRUE ~ .x)) %>% 
             bind_cols(cars, .)
    
    head(out)
    #  speed dist  km    mt
    #1     4    2  16 0.024
    #2     4   10  80 0.120
    #3     7    4  56 0.084
    #4     7   22 308 0.462
    #5     8   16 256 0.384
    #6     9   10 180 0.270
    

提交回复
热议问题