Relative Content

Tag Archive for rdplyrconditional-statementssamplemutate

Groupwise replace NA’s with sampled value from non NA’s using dplyr

I have a dataframe with missing NA values in column X1 and a grouping variable group. I want to replace all NA values with a value sampled from the non-NA values of that group. This should be done for all groups except for one (group==C). For this conditional replacement with resample data I tried if/else and case_when within the mutate command of dplyr, however without success. I guess this is because the TRUE and FALSE are both evaluated before assessing the condition. (The case_when condition works and selects the appropriate cases as shown when calculating X2, however using the sample command causes a problem.)