mutate two or more columns if case_when is used

前端 未结 2 1903
刺人心
刺人心 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 21:53

    Discover this solution, but is a bit weird and tricky

    mutate_when <- function (data, ...) {
      dots <- eval (substitute (alist(...)))
      for (i in seq (1, length (dots), by = 3)) {
        condition <- eval (dots [[i]], envir = data)
        mutations <- eval (dots [[i + 1]], envir = data [condition, ])
        data[condition, names(mutations)] <- mutations
        mutations_else <- eval (dots [[i + 2]], envir = data [!condition, ])
        data[!condition, names(mutations)] <- mutations_else
      }
      data
    }
    
    cars %>%
      mutate(
        km = speed * dist, 
        mt = km/1000
      ) %>%
      mutate_when(
        speed < 20, 
        list (
          km = km * 2,
          mt = mt * 3
        ),
        list (
          0
        )
      )
    

    Gives

       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
    

提交回复
热议问题