I would like to count the NA of a set of variables with a for loop.
confounders<-c("Age", "Sex", "Race", "education")
missings = list()
for (var in confounders) { missings[[var]] = with(data_all, sum(is.na(var[[1]])))}
missings
I only get the output zero for every variable, which is incorrect:
> missings
$Age
[1] 0
$Sex
[1] 0
$Race
[1] 0
$education
[1] 0
> with(data_all, sum(is.na(education)))
[1] 55
CodePudding user response:
You need to tell R to evaluate var
a variable, not as a string (e.g. Age, not "Age"). You can do this with get(eval())
data_all=data.frame(Age=c(34,40,50,40),Sex=c("F","M","M","F"), Race=c(NA,NA,NA,NA), education=c("high","low","low",NA))
confounders<-c("Age", "Sex","Race", "education")
missings = list()
for (var in confounders) {
missings[[var]] = with(data_all, sum(is.na(get(eval(var)))))
}
missings
CodePudding user response:
Try this
confounders<-c("Age", "Sex", "Race", "education")
missings = list()
for (var in confounders) {
missings[[var]] = sum(is.na(data_all[[var]]))
}
missings