且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在基于多列的条件下使用dplyr mutate

更新时间:2023-02-02 20:26:44

如果您这样做,它将按预期工作:

It works as intended if you do:

mutate(V, V4 = case_when(
  V1 == 2 | V2 == 2 | V3 == 2 ~ 2,
  V1 == 1 | V2 == 1 | V3 == 1 ~ 1,
  V1 == 0 | V2 == 0 | V3 == 0 ~ 0
))

此外,您应该使用data.frame()data_frame()tibble()之一而不是cbind(),以使V对象更符合dplyr函数,后者期望使用数据帧而不是矩阵(即由cbind()产生.

Also, you should use one of data.frame(), data_frame() or tibble() instead of cbind() to make the V object more compliant to dplyr functions, which expect a data frame instead of a matrix (which is what gets produced by cbind().