如果使用case_when,则将两列或更多列突变 [英] mutate two or more columns if case_when is used

查看:67
本文介绍了如果使用case_when,则将两列或更多列突变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 case_when 函数用于data.frame的一堆列.

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

这种情况不会返回 mutate

cars %>% mutate (
  km = speed * dist,
  mt = km / 1000
) %>%
mutate (
  .funs = case_when(
    (speed < 20 ) ~ {
      km = km * 2 
      mt = mt * 3
    }
  )
)

谢谢

推荐答案

我们可以使用 mutate_at

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


如果我们需要为每个列使用单独的值进行计算,请使用 map2 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

这篇关于如果使用case_when,则将两列或更多列突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆