使用 case_when 替代嵌套的 ifelse 语句。

huangapple go评论65阅读模式
英文:

Using case_when for nested ifelse statements

问题

您尝试创建一个新的变量B,根据A1、A2和A3的值来填充,但在A1和A2都缺失的情况下,它返回了NA而不是A3。您可能错过了一个条件,您可以使用以下方式来修复它:

adf %>%
  mutate(
    B = case_when(
          !is.na(A1) ~ A1, 
          is.na(A1) & !is.na(A2) ~ A2, 
          is.na(A1) & is.na(A2) & !is.na(A3) ~ A3,
          TRUE ~ NA
        )
  )

这个修改会确保当A1和A2都缺失,但A3存在时,将值填充为A3。

英文:

I have data that looks like this sample:

 A1<-seq(3,5); A2<-seq(1,5); A3<-seq(2,8)
length(A1)<-7; length(A2)<-7; length(A3)<-7
adf <-as.data.frame(cbind(A1,A2,A3))

 A1 A2 A3
1  3  1  2
2  4  2  3
3  5  3  4
4 NA  4  5
5 NA  5  6
6 NA NA  7
7 NA NA  8

I would like to create a new variable that pulls from A1, unless it is a missing value, in which case it pulls from A2, unless there is also a missing value, in which case it pulls from A3. This is what I have tried:

 adf %>% 
mutate(
B = case_when(
      !is.na(A1) ~ A1, 
      is.na(A1) ~ A2, 
      (is.na(A1) & is.na(A2) & !is.na(A3)) ~ A3
    )
  )

  A1 A2 A3  B
1  3  1  2  3
2  4  2  3  4
3  5  3  4  5
4 NA  4  5  4
5 NA  5  6  5
6 NA NA  7 NA
7 NA NA  8 NA

This works for the most part but as you can see, in cases where both A1 and A2 are missing, but A3 is not, it return NAs instead of A3. What am I missing?

答案1

得分: 1

The coalesce function handles just this use case. You can do:

adf %>% mutate(B=coalesce(A1, A2, A3))

giving:

  A1 A2 A3 B
1  3  1  2 3
2  4  2  3 4
3  5  3  4 5
4 NA  4  5 4
5 NA  5  6 5
6 NA NA  7 7
7 NA NA  8 8
英文:

The coalesce function handles just this use case. You can do:

adf %>% mutate(B=coalesce(A1, A2, A3))

giving:

  A1 A2 A3 B
1  3  1  2 3
2  4  2  3 4
3  5  3  4 5
4 NA  4  5 4
5 NA  5  6 5
6 NA NA  7 7
7 NA NA  8 8

huangapple
  • 本文由 发表于 2023年6月9日 04:37:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定