Working through survey data and I need to perform some imputing for occasional NA's popping up within the different questions of a measure. I want to replace NA with the row mean, but only on the condition that there are no more than 2 NA's across the row. Any tips on how to achieve this would be amazing.
I've tried using the code below (with some example data), but that doesn't allow me to control for how many NA's in a row that are acceptable.
data <- data.frame(
var_1 = c(2,3,NA,2,3,5,NA,3),
var_2 = c(3,4,2,3,1,3,NA,2),
var_3 = c(NA,3,2,5,4,2,NA,2),
var_4 = c(NA,3,NA,4,1,2,NA,1),
var_5 = c(NA,4,2,3,2,3,NA,2),
var_6 = c(4,2,1,NA,2,5,NA,3),
var_7 = c(3,2,1,2,2,4,NA,3))
data_fix <- data %>%
mutate(var_1 = ifelse(is.na(var_1),rowMeans(data[row_number(),], na.rm = T),var_1),
var_2 = ifelse(is.na(var_2),rowMeans(data[row_number(),], na.rm = T),var_2),
var_3 = ifelse(is.na(var_3),rowMeans(data[row_number(),], na.rm = T),var_3),
var_4 = ifelse(is.na(var_4),rowMeans(data[row_number(),], na.rm = T),var_4),
var_5 = ifelse(is.na(var_5),rowMeans(data[row_number(),], na.rm = T),var_5),
var_6 = ifelse(is.na(var_6),rowMeans(data[row_number(),], na.rm = T),var_6),
var_7 = ifelse(is.na(var_7),rowMeans(data[row_number(),], na.rm = T),var_7))