[R] Using loops to run functions over a list of variables
rapton
mattcomm at gmail.com
Tue May 12 17:55:31 CEST 2009
Hello,
I have a data set with many variables, and often I want to run a given
function, like summary() or cor() or lmer() etc. on many combinations of one
or more than one of these variables. For every combination of variables I
want to analyze I have been writing out the code by hand, but given that I
want to run many different functions over dozens and dozens of variables
combinations it is taking a lot of time and making for very inelegent code.
There *has* to be a better way! I have tried looking through numerous
message boards but everything I've tried has failed.
It seems like loops would solve this problem nicely.
(1) Create list of variables of interest
(2) Iterate through the list, running a given function on each variable
I have a data matrix which I have creatively called "data". It has
variables named "focus" and "productive".
If I run the function summary(), for instance, it works fine:
summary(data$focus)
summary(data$productive)
Both of these work.
If I try to use a loop like:
factors <- c("data$focus", "data$productive")
for(i in 1:2){
summary(get(factors[i]))
}
It given the following errors:
Error in get(factors[i]) : variable "data$focus" was not found
Error in summary(get(factors[i])) :
error in evaluating the argument 'object' in selecting a method for
function 'summary'
But data$focus *does* exist! I could run summary(data$focus) and it works
perfectly.
What am I doing wrong?
Even if I get this working, is there a better way to do this, especially if
I have dozens of variables to analyze?
Any ideas would be greatly appreciated!
--
View this message in context: http://www.nabble.com/Using-loops-to-run-functions-over-a-list-of-variables-tp23505399p23505399.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list