I am trying to create a new variable that replaces the total scores of an old variable assuming certain conditions are met. The code I have tried is:
Baseline_Data_V2 <- Baseline_Data_V1 %>%
mutate(NewVariable = case_when(KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 3 ~ -3.711,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 4 ~ -2.474,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 5 ~ -1.813,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 6 ~ -1.312,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 7 ~ -0.88,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 8 ~ -0.476,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 9 ~ -0.079,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 10 ~ 0.327,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 11 ~ 0.757,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 12 ~ 1.227,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 13 ~ 1.77,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 14 ~ 2.475,
KY27SOC_NA_Total == 1 &
is.na(KY27SOC2) &
KY27SOC_Total_Adjusted == 15 ~ 3.754,
.default = OldVariableScores))
#> Error in Baseline_Data_V2 %>% mutate(NewVariable = case_when(KY27SOC_NA_Total == : could not find function "%>%"
Created on 2023-08-03 with reprex v2.0.2
Basically, if the total number of NAs in the variable KY27SOC_NA_Total is 1, and KYSOC2 is an NA value, and the total of KYSOC_Total is 3, I want the new variable to have a value of -3.711. Else, I want the value of the OldVariableScores to be upheld. This is then replicated for different total scores of KYSOC_Total, with the other two conditions always being upheld, and the value of the OldVariableScores being upheld if the conditions are not met (this will range from 3 to 20, but can also have NAs). I have tried multiple options but basically the outcome is always a column full of NAs. If anyone has any idea of where I am going wrong, I'd really appreciate your feedback. Thank you.
P.S - I found that there was an error with one of the variables, that is why it was not working. Otherwise this code seems to do the trick. It seems that the suggestion below also works, so I will give it a +1. My apologies for initially uploading an image, reprex() in renv environment was not working so I foolishly decided to upload the image. THANK YOU to all who spent time looking at this, it is much appreciated!!