[R] looping through variables

Adaikalavan Ramasamy a.ramasamy at imperial.ac.uk
Wed Sep 24 20:39:23 CEST 2008

Perhaps what you want is get().

    apple <- rnorm(5)
    orange <- runif(5)

    fruits <- c("apple", "orange")

    fruit.data <- NULL
    for( fruit in fruits ){
       v <- get(fruit)
       fruit.data <- cbind(fruit.data, v)
    colnames(fruit.data) <- fruits


Here the resulting output is a matrix which works if all of your inputs 
have the same length. If they don't, then you probably want to use a 
list instead. Also have a look at assign().

Regards, Adai

K. Fleischer wrote:
> Hello everyone,
> I have the following problem:
> My analysis includes many predictor variables (>50) in the form of 
> raster maps (asc), but I am trying to avoid having to type all their 
> names over and over again in the analysis (e.g. for vectorisation, for 
> deletion of NA's, etc.)
> So ideally I would like to store them in some way that their names 
> only have to be typed once and can always be referred back to.
> First step would be to automate the vectorisation of the raster maps:
> # these are the raster maps which need to combined somehow ??
> variables <- (temperature, precipitation, elevation, vegcover) 
> VariablesNew=c()
> For (i in 1:length(variables)) {
> Varnew <- as.vector(variables[i])
> VariablesNew <- cbind(VariablesNew, Varnew)
> }
> This should return a data frame called VariablesNew with each column 
> representing one of the variables. 
> So the BIG QUESTION is how to input the variable names that they can 
> be referred to easily and, the variable itself can be pulled out and 
> not just its name!!
> I believe this cant be too difficult??
> Thanx in advance,
> Katrin
> ______________________________________________
> 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.

More information about the R-help mailing list