Hi everyone.
I had prior success in creating an ifelse() statement for populating a column based on conditions for two variables (thanks to @andresrcs). However, I am now stuck on nesting ifelse() to set more conditions based on the same observation conditions as the first ifelse() statement.
I'm assigning "YES" or "NO" in a column based on "PATIENT_ID" and "DATE", with multiple patients being present in the data frame. Here is what I have attempted so far.
#Loading relevant packages
library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.5.3
#> Warning: package 'ggplot2' was built under R version 3.5.3
#> Warning: package 'tibble' was built under R version 3.5.3
#> Warning: package 'tidyr' was built under R version 3.5.3
#> Warning: package 'readr' was built under R version 3.5.3
#> Warning: package 'purrr' was built under R version 3.5.3
#> Warning: package 'dplyr' was built under R version 3.5.3
#> Warning: package 'stringr' was built under R version 3.5.3
#> Warning: package 'forcats' was built under R version 3.5.3
library(dplyr)
library(lubridate)
#> Warning: package 'lubridate' was built under R version 3.5.3
#>
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#>
#> date
#Extracted variables and observations from my data frame in question
PATIENT_ID <- c("-2147483646", "-2147483646", "-2147483646", "-2147483646", "-2147483646", "-2147483645", "-2147483645", "-2147483645", "-2147483645")
DATE <- c("06-08-2018", "20-08-2018", "01-10-2018", "04-02-2019","22-07-2019", "16-08-2018", "30-08-2018", "11-10-2018", "27-02-2019")
VISIT_DAY <- ""
#Example data frame with extracted variables and observations
df1 <- data.frame(PATIENT_ID, DATE, VISIT_DAY)
df1$DATE <- as.Date(df1$DATE, format = "%d-%m-%Y") #Converting to date
#Successful code to populate "YES" for met conditions of 1st patient
df1 <- df1 %>%
mutate(VISIT_DAY = if_else((PATIENT_ID == "-2147483646" & DATE %in% dmy(c("06-08-2018", "20-08-2018", "01-10-2018", "04-02-2019","22-07-2019"))), "YES", "NO"))
#Unsuccessful nesting, still works for first patient but not the second
df1 <- df1 %>%
mutate(VISIT_DAY = if_else((PATIENT_ID == "-2147483646" & DATE %in% dmy(c("06-08-2018", "20-08-2018", "01-10-2018", "04-02-2019","22-07-2019"))), "YES", "NO",
if_else((PATIENT_ID == "-2147483645" & DATE %in% dmy(c("16-08-2018", "30-08-2018", "11-10-2018", "27-02-2019"))), "YES", "NO")))
Any help with this would be much appreciated. Thanks!