Lowpar
Lowpar

Reputation: 907

ifelse statement returning error in dplyr

looking to create a binary indicator variable for a t.test and I am getting an error.

  fd <- fd %>%
    mutate(Con = ifelse(Intro1 != 2 | Intro1 != 4,0,
           ifelse(Intro2 != 2 | Intro2 != 4, 1,"NA")))

Error: incompatible types, expecting a numeric vector

    > str(fd$Intro2 )
    int [1:6299] NA NA NA 3 NA NA NA NA NA NA ...
    > str(fd$Intro1 )
    int [1:6299] NA NA NA NA NA NA NA NA NA NA ...

Is it because of the nas? I tried

  fd <- fd %>%
        select(c(Intro1 , Intro2)) %>%
        na.omit  %>%
        mutate(Con = ifelse(Intro1 != 2 | Intro1 != 4,0,
             ifelse(Intro2 != 2 | Intro2 != 4, 1,"NA")))

Essentially what I would like to do is loop through all the rows and apply a 0 if Intro1 is not 2 or 4, and a 1 if Intro2 is not 2 or 4.

Upvotes: 0

Views: 287

Answers (1)

shosaco
shosaco

Reputation: 6175

Using dplyr case_when syntax (which might be more readable than nested ifelse statements):

> fd <- data_frame(Intro1 = c(NA,NA,NA, 1:5), Intro2 = c(NA,1:5, NA,NA))
> fd %>% mutate(Con = case_when(
     ! Intro1 %in% c(2,4) ~ 0,
     ! Intro2 %in% c(2,4) ~ 1
 ))

# A tibble: 8 x 3
  Intro1 Intro2   Con
   <int>  <int> <dbl>
1     NA     NA     0
2     NA      1     0
3     NA      2     0
4      1      3     0
5      2      4    NA
6      3      5     0
7      4     NA     1
8      5     NA     0

Upvotes: 2

Related Questions