简体   繁体   中英

Using dplyr mutate with conditions based on multiple columns

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM