Skip to content
Prev 274066 / 398506 Next

Mean or mode imputation fro missing values

Yes thank you Gu?
I am just trying to do this as a rough step and will try other
imputation methods which are more appropriate later.
I am just learning R, and was trying to do the for loop and
f-statement by hand but something is going wrong?

This is what I have until now:

*****fake array:
age<- c(5,8,10,12,NA)
a<- factor(c("aa", "bb", NA, "cc", "cc"))
b<- c("banana", "apple", "pear", "grape", NA)
df_test <- data.frame(age=age, a=a, b=b)
df_test$b<- as.character(df_test$b)

for (var in 1:ncol(df_test)) {
	if (class(df_test$var)=="numeric") {
		df_test$var[is.na(df_test$var)] <- mean(df_test$var, na.rm = TRUE)
		} else if (class(df_test$var)=="character") {
		Mode(df_test$var[is.na(df_test$var)], na.rm = TRUE)
		}
}

Where 'Mode' is the function:

function (x, na.rm)
{
    xtab <- table(x)
    xmode <- names(which(xtab == max(xtab)))
    if (length(xmode) > 1)
        xmode <- ">1 mode"
    return(xmode)
}


It seems as it is just ignoring the statements though, without giving
any error?Does anybody have any idea what is going on?

Thank you very much for all the great help!
-f

2011/10/11 Weidong Gu <anopheles123 at gmail.com>: