[R] Assigning objects to variable and variable to list in a for loop

Joshua Wiley jwiley.psych at gmail.com
Fri Feb 3 11:22:30 CET 2012


Hi Johannes,

There is a relatively elegant solution if you assign in a list:

reslist <- lapply(1:3, function(x) runif(5))
names(reslist) <- paste("result", LETTERS[1:3], sep = "_")

Cheers,

Josh

On Fri, Feb 3, 2012 at 2:07 AM, Johannes Radinger <JRadinger at gmx.at> wrote:
> Hello,
>
> I want to use a for loop for repeadely calculating
> a maxent model (package dismo, function maxent()) which
> creates an object of the class maxent (S4).
> I want to collect all the resulting object in a list.
>
> I tried to simplify my for loop to explain what I want.
> There are two problems/questions:
> 1) How can I create the new variables in the loop (using paste) and assign the objects
> 2) How can I collect the results (objects) in a list
>
> X <- factor(c("A","B","C"))
>
> for(in in X){
>        as.name(paste("result","X",sep="_")) <- runif(5) #any object
>        # create list of objects with names
>        }
>
> I read something about assign(), but that assigns a value and not an object to a variable. Some time ago I did something similar but with a matrix: Thus I created an empty matrix before the loop and indexed the matrix inside the loop to assign values. But here it is about assigning ojects to variables and coercing these to a list.
>
> Any suggestions are mostly welcomme.
>
> Thank you,
>
> best regards,
> Johannes Radinger
> --
>
> ______________________________________________
> 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.



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list