I was trying to fill NA values from column 'Income' with the mean of the column based on the gender column, so if 'M' has a NA value, insert one from the mean of all 'M' people (except NA values):
GENDER|INCOME
M| 1
M| 2
M| 3
M| NA
F| 4
F| 4
F| 5
F| NA
GENDER|INCOME
M| 1
M| 2
M| 3
M| 2
F| 4
F| 4
F| 5
F| 4.33
I tried the aggregate method but it gives you a list that, if I try to input in my dataset, it gives me an error in order to write a CSV. It works perfectly to get the values, but I don't know how to input these values but manually. This is my code so far:
df$INCOME[is.na(df$INCOME)] <- aggregate(.~df$GENDER, df, FUN = mean, na.rm = TRUE)
Thank you for any help!