I have a complicated question that I will try to simplify by simplifying my dataset. Say I have 5 variables:
df$Id <- c(1:12) df$Date <- c(NA,NA,a,a,b,NA,NA,b,c,c,b,a) df$va <- c(1.1, 1.4, 2.5, ...) #12 randoms values df$vb <- c(5.9, 2.3, 4.7, ...) #12 other random values df$vc <- c(3.0, 3.3, 3.7, ...) #12 more random values
Then I want to create a new variable that takes the value from va, vb, or vc if the date is equal to a, b, or c. I had tried a nested if-else, which did not work. I also tried:
df$new[df$date=='a' & !is.na(df$date)] <- df$va df$new[df$date=='b' & !is.na(df$date)] <- df$vb df$new[df$date=='c' & !is.na(df$date)] <- df$vc
This correctly left NA's in the new variable where Date=NA, however the values provided were not from va, vb, or vc, but some other value altogether. How can I get df$new to equal va if the date is 'a', vb if the date is 'b', and vc if the date is 'c'?