Using dplyr mutate with conditions based on multiple columns

空扰寡人 提交于 2019-12-23 04:49:08

问题


Without NAs, the following code would work as intended: if the first row has any 2's in it, the new variable takes a value of 2; if not, I want to check if any of the values are 1; if not, check if any are 0; if not, then all must be NA.

Once I add NAs into the data frame, it no longer works and I can't seem to figure out why:

V1 <- c(NA,1,2,0,0)
V2 <- c(0,0,2,1,1)
V3 <- c(NA,0,2,1,0)

V <- cbind(V1,V2,V3)

V <- mutate(V,V4 = ifelse(V1 == 2|V2==2|V3==2, 2, 
ifelse(V1==1|V2==1|V3==1, 1, ifelse(V1==0|V2==0|V3==0,0,NA))))

Intended output:

  V1 V2 V3 V4
1 NA  0 NA  0
2  1  0  0  1
3  2  2  2  2
4  0  1  1  1
5  0  1  0  1

Actual output:

  V1 V2 V3 V4
1 NA  0 NA NA
2  1  0  0  1
3  2  2  2  2
4  0  1  1  1
5  0  1  0  1

回答1:


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
))

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().



来源:https://stackoverflow.com/questions/48038236/using-dplyr-mutate-with-conditions-based-on-multiple-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!