I am working with a panel data set so the same question has been asked several times over the span of a few years. I want to create a new variable with the values of the oldest wave. If there are NAs in this oldest wave I want to overwrite ONLY these with the "newer" values of the second wave. And if there are missing values in the first and second wave I want to overwrite only those with the values of the third wave. Therefore, I am working with mutate and case_when and combining conditions in case_when. However, either I can't overwrite the old values with newer ones or I produce almost only missing values bc the condition is almost never true. In that second case I would like to know how to firstly take the values from the first wave and ONLY replace them in the case of NAs. I tried the following variants:
1.
gles_panel2 <- gles_panel2 %>%
mutate(test3 = case_when(kp7_180 %in% c(2) ~ "1",
kp7_180 %in% c(1, 6) ~ "0",
kp7_180 < 1 ~ "NA",
kp7_180 %in% NA & kp10_2780 == 2 ~ "1",
kp7_180 %in% NA & kp10_2780 == 1 ~ "0",
kp7_180 %in% NA & kp10_2780 < 1 ~ "NA"))
2.
gles_panel2 <- gles_panel2 %>%
mutate(test3 = case_when(kp7_180 %in% c(2) ~ "1",
kp7_180 %in% c(1, 6) ~ "0",
kp7_180 < 1 ~ "NA"))
gles_panel2 <- gles_panel2 %>%
mutate(test3 = case_when(test3 %in% NA & kp10_2780 == 2 ~ "1",
test3 %in% NA & kp10_2780 == 1 ~ "0",
test3 %in% NA & kp10_2780 < 1 ~ "NA"))
I achieved it with the nested ifelse-function (see below) but I want to get the same result with case_when.
gles_panel2 <- gles_panel2 %>%
mutate(nwahl2013_test = ifelse(kp7_180==2,1,ifelse(kp7_180 %in% c(1,6),0, NA)))
gles_panel2 <- gles_panel2 %>%
mutate(nwahl2013_test = ifelse(is.na(nwahl2013_test) & kp10_2780==2,1,ifelse(is.na(nwahl2013_test) & kp10_2780==1,0, nwahl2013_test)))