Alice
Alice

Reputation: 99

Nesting ifelse in R

I'm trying to nest ifelse in R to create a new vector C, where if both vectors A and B are missing, then NA; otherwise, if either vector contains 1, then "Yes"; otherwise, "No". Example:

A  B  C
1  1  Yes
1  0  Yes
0  1  Yes
0  0  No
NA 1  Yes
0  NA No
NA NA NA

The below is what I've been playing around with in various iterations, but I can't get it to work correctly. Any suggestions?

df <- df %>% mutate(C=ifelse((is.na(A) & is.na(B)), NULL, ifelse((A==1 | B==1), "Yes", "No")))

(Perhaps there's a better way which doesn't use ifelse at all, which I'd also be open to, but for my own understanding it would be nice to know how to get this way to work as well!)

Many thanks!

Upvotes: 2

Views: 86

Answers (4)

Iroha
Iroha

Reputation: 34751

Here is an alternative to ifelse():

df$C <- c("No", "Yes")[(rowMeans(df, na.rm = TRUE) > 0) + 1]

df
   A  B    C
1  1  1  Yes
2  1  0  Yes
3  0  1  Yes
4  0  0   No
5 NA  1  Yes
6  0 NA   No
7 NA NA <NA>  

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 102710

One option via nested ifelse:

df$C <- ifelse(rowSums(df, na.rm = TRUE) > 0,
    "Yes",
    ifelse(rowSums(is.na(df)) < 2,
        "No",
        "NA"
    )
)

which gives

> df
   A  B   C
1  1  1 Yes
2  1  0 Yes
3  0  1 Yes
4  0  0  No
5 NA  1 Yes
6  0 NA  No
7 NA NA  NA

Data

df <- structure(list(A = c(1L, 1L, 0L, 0L, NA, 0L, NA), B = c(1L, 0L, 
1L, 0L, 1L, NA, NA)), row.names = c(NA, -7L), class = "data.frame")

Upvotes: 1

lrnv
lrnv

Reputation: 1106

In base R, you could do somehting like :

df$C <- ifelse(is.na(df$A)*is.na(df$B),NA,ifelse(ifelse(is.na(df$A),FALSE,df$A==1) + ifelse(is.na(df$B),FALSE,df$B==1)>0,"Yes","No"))

?

Upvotes: 0

Bulat
Bulat

Reputation: 6979

One option would be to use case_when function from dplyr package.

# This was not tested, but should give your a flavour of how it might work
df <- df %>% mutate(
  C = dplyr::case_when(
    is.na(A) & is.na(B) ~ NA,
    A == 1 | B == 1 ~ "Yes",
    TRUE ~ "No"
  )
)

Upvotes: 0

Related Questions