I need help to a solution. I have tried reading many earlier questions and answer but without a solution to my case. I want to keep the values in every variable but in the variable Udd I only want to change the NA values but keep the rest as it is.
Every time Udd is NA, I want it to change according to Edu.
When Edu is from 1:7, I want Udd to be 1. When Edu is from 8:11, I want Udd to be 2. When Edu is from 12 and above, I want Udd to be 3.
library(dplyr)
ID <- c(1,2,3,4,5,6,7,8,9,10)
Edu <- c(4,7,9,13,15,18,11,10,12,8)
Udd <- c(1,NA,2,NA,3,3,2,NA,3,2)
d <- data.frame(ID, Edu, Udd)
d <- d %>%
mutate(Udd = case_when(is.na(Udd) & Edu < 8 ~ 1,
is.na(Udd) & Edu[c(8,11)] ~ 2,
is.na(Udd) & Edu > 11 ~ 3))
It changes NA but returns rest as NA. I only want it to change the NA values, and keep the Udd values that are not NA as they were.
Changed the vector to have an %in% statement and added an else statement.
d %>%
mutate(Udd = case_when(is.na(Udd) & Edu < 8 ~ 1,
is.na(Udd) & Edu %in% c(8:11) ~ 2,
is.na(Udd) & Edu > 11 ~ 3,
TRUE ~ Udd))