简体   繁体   中英

using a character vector with with()

I am trying to create a huge summary table and want to loop through a set of variables and create simple frequencies. There's a mix of variables (eg, age, gender), but they are all going to be dichotomised. I've tried to create a character vector of variables and their dichotomisation ('vars' below), and then using with to apply them to the data. Sadly this isn't working.

vars = c("SEX=='M'",'BMI<25')
data = data.frame(SEX=c('M','F','M'), BMI=c(10,20,30)) # dummy data
for (this.var in vars){
   true.false.var = with(data,this.var)
   tab = table(true.false.var)
}

Try

vars = c("SEX=='M'",'BMI<25')
data = data.frame(SEX=c('M','F','M','M'), BMI=c(10,20,30,40)) # dummy data
lapply(vars, function(x) {
  with(data, table(eval(parse(text=x))))
})
# [[1]]
# 
# FALSE  TRUE 
# 1     3 
# 
# [[2]]
# 
# FALSE  TRUE 
# 2     2

They key is to use tab = with(data, table(eval(parse(text=true.false.var)))) in your code. eval(parse()) tells R that the string is an expression. And without the with(data, ...) statement, R would search for objects named SEX and BMI , which are not available in the environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM