It is the kind of critical information you have precise at the beginning. We can't guess...
Why do no want to use some libraries that exists to make your life easier ? Sometimes you don't want to have no dependencies but when doing some analysis, it does not worth it. Moreover, libraries like dplyr are optimized in performance and in stability to help you.
With this in mind, about your code now. Some advices :
When you are trying to debug something try doing it step by step.
- is
df[,which(colSums(is.na(df))>0)] working ?
- is
df[,which(colSums(is.na(df))>0)][is.na(df[,which(colSums(is.na(df))>0)])] ?
- ...
You will encounter error code that will help you understand.
Here, you are trying to do all NA replacement in all column in one step. One easiest thing is to do it by column:
apply(df, 2, function(vec) {
vec[is.na(vec)] <- mean(vec, na.rm = T)
})
This snippet will apply a function to each column (2). The function applies on a column, search for NA and replace by the mean of the column.
In your code there is some issue with the dimension, and the way you are trying to replace. I won't go into detail but you have to take care of what is your right hand side (RHS) that you want to assign to your left hand sign (LHS). When I try you code the LHS throws an error.
Hope it is clearer to you now.