I'm new to R and I use the package MICE for multiple imputation.
For basic analysis I want to calculate mean for different columns using subsets.
I have > 70 columns named "Var_1"
, "Var_2"
and so on.
The following statement works so far:
meanVal <- with(imp, exp = mean(subset(Var_1, Var_2 == 1)))
saveValue <- mean(unlist(meanVal$analyses))
At this point I want to use a function, because I have different conditions and a list of vars for which I want to calculate mean values.
doMean(imp, varlist, filter) {
for (i in 1:length(varlist) {
meanVal <- with(imp, exp = mean(subset(varlist[i], Var_2 == filter)))
saveValue[i] <- mean(unlist(meanVal$analyses))
}
}
#print(varlist[1]) is "Var_1"
#print(varlist[2]) is "Var_4"
#...
The expression varlist[i]
is incorrect and I have no idea how to typecast it correctly.
The warning message is argument is not numeric or logical: returning NA
.
I have tried noquote()
and different as.function_name()
-functions.
Edit: A small example
library(mice)
data("nhanes2")
head(nhanes2)
impZero <- mice(nhanes2, maxit = 0)
imp <- mice(nhanes2, maxit = 5, method = impZero$method, predictorMatrix = impZero$predictorMatrix, printFlag = FALSE)
rname <- c('chl', 'bmi')
#Working
MeanRes <- with(imp, exp = mean(subset(chl, bmi > 25)))
res <- mean(unlist(MeanRes$analyses)) #200.688888888
enter code here
#Not Working
MeanRes <- with(imp, exp = mean(subset(rname[1], bmi > 25)))
res <- mean(unlist(MeanRes$analyses)) #NA
Thank you very much in advance for your help!