samedi 16 mai 2020

Some conditions in nested ifelse taken into account

I struggle with nested ifelse. I want to create a new variable using dplyr::mutate based on values of other variables. See the reproductible example below.

library(dplyr)
library(hms)

# make a test dataframe
datetime <- as.POSIXct(c("2015-01-26 10:10:00 UTC","2015-01-26 10:20:00 UTC","2015-01-26 10:30:00 UTC", "2015-01-26 10:40:00 UTC","2015-01-26 10:50:00 UTC","2015-01-26 11:00:00 UTC","2015-01-26 00:10:00 UTC","2015-01-26 11:20:00 UTC","2015-01-26 11:30:00 UTC","2017-03-10 10:00:00 UTC"))
time <- hms::as_hms(datetime)
pco2_corr <- c(90,135,181,226,272,317,363,NA,454,300)
State_Zero <- c(NA,NA,1,rep(NA,7))
State_Flush <- c(rep(NA,4),1,rep(NA,5))
z <- tibble(datetime, time, pco2_corr, State_Zero, State_Flush)

# now create a new variable
z <- z %>% 
  dplyr::mutate(pco2_corr_qf = ifelse(is.na(pco2_corr), 15,
                               ifelse((State_Zero >= 1 | State_Flush >= 1), 4,
                                      ifelse(pco2_corr < 100 | pco2_corr > 450, 7,
                                             ifelse((time >= "00:00:00" & time <= "01:30:00") | 
                                                      (time >= "12:00:00" & time <= "13:00:00"), 16,
                                                    ifelse((datetime >= "2017-03-10 08:00:00" & 
                                                              datetime < "2017-03-21 20:00:00"), 99,
                                                           1))))))
z
# A tibble: 10 x 6
   datetime            time   pco2_corr State_Zero State_Flush pco2_corr_qf
   <dttm>              <time>     <dbl>      <dbl>       <dbl>        <dbl>
 1 2015-01-26 10:10:00 10:10         90         NA          NA           NA
 2 2015-01-26 10:20:00 10:20        135         NA          NA           NA
 3 2015-01-26 10:30:00 10:30        181          1          NA            4
 4 2015-01-26 10:40:00 10:40        226         NA          NA           NA
 5 2015-01-26 10:50:00 10:50        272         NA           1            4
 6 2015-01-26 11:00:00 11:00        317         NA          NA           NA
 7 2015-01-26 00:10:00 00:10        363         NA          NA           NA
 8 2015-01-26 11:20:00 11:20         NA         NA          NA           15
 9 2015-01-26 11:30:00 11:30        454         NA          NA           NA
10 2017-03-10 10:00:00 10:00        300         NA          NA           NA

The first two ifelse work fine but the next three do not. The new variable pco2_corr_qf should not have any NA but values 7, 16, 99 and 1.

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire