Hello, This is a beginner question. I am trying to loop through numbered variables with "apply" to calculate weighted means. My data is "data", the variables are "var1" to "var100", the weight is "weight". The command works using sapply(paste('data$var', 1:100, sep=''), function(x) weighted.mean(eval(parse(text=x)), data$weight)) but is there a way to avoid eval(parse())? Thank you, Daniel
Have you read "An Introduction to R". If not, please do so before osting and pay particular attention to the section on indexing. If so, re-read the sections on indexing. For a terser exposition, ?"[" -- Bert On Mon, Aug 27, 2012 at 7:11 AM, Daniel Caro <dcarov at gmail.com> wrote:> Hello, > > This is a beginner question. I am trying to loop through numbered > variables with "apply" to calculate weighted means. My data is "data", > the variables are "var1" to "var100", the weight is "weight". The > command works using > > sapply(paste('data$var', 1:100, sep=''), function(x) > weighted.mean(eval(parse(text=x)), data$weight)) > > but is there a way to avoid eval(parse())? > > Thank you, > Daniel > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.-- Bert Gunter Genentech Nonclinical Biostatistics Internal Contact Info: Phone: 467-7374 Website: http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm
On Aug 27, 2012, at 7:11 AM, Daniel Caro wrote:> Hello, > > This is a beginner question.You should read the Posting Guide. (As well as following Bert's suggestion to work through "Intro to R".> I am trying to loop through numbered > variables with "apply" to calculate weighted means. My data is "data", > the variables are "var1" to "var100", the weight is "weight". The > command works using > > sapply(paste('data$var', 1:100, sep=''), function(x) > weighted.mean(eval(parse(text=x)), data$weight)) > > but is there a way to avoid eval(parse())?I'm guessing you want: library( <some package which was not named> ) lapply(data, function(x) weighted_mean(x, data$weight)) (I'm was guessing that weighted_mean was from the Hmisc package (but its similar function has a different name), but at any rate, it is better practice to indicate what package holds non-core functions. I also think it is better practice to use named arguments in function calls and to not use teh name "data" for objects, since it is also a function name.) ?data -- David Winsemius, MD Alameda, CA, USA