否则嵌套嵌套

我得到了错误的结果,我做错了什么?

df <- data.frame(x=c(1,1,NA),y=c(1,NA,NA),z=c(NA,NA,NA))
df <-mutate(df,result=ifelse(is.na(x),NA,ifelse(any(!is.na(y),!is.na(z)),1,0)))

我得到这个(data [2,4] == 0)

   x  y  z result
1  1  1 NA      1
2  1 NA NA      1
3 NA NA NA     NA

代替这个:

df_wanted <- data.frame(x=c(1,1,NA),y=c(1,NA,NA),z=c(NA,NA,NA), result=c(1,0,NA))

   x  y  z result
1  1  1 NA      1
2  1 NA NA      0
3 NA NA NA     NA

评论
svero
svero

We can use | instead of any because any returns a single TRUE/FALSE as output

with(df, any(!is.na(y), !is.na(z)))
#[1] TRUE

and that gets recycled for the entire column instead we need to do this for each row and this can be accomplished with |

library(dplyr)
df %>%
   mutate(result = ifelse(is.na(x), NA, ifelse(!is.na(y)|!is.na(z), 1, 0)))
#   x  y  z result
#1  1  1 NA      1
#2  1 NA NA      0
#3 NA NA NA     NA
点赞
评论