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

Steve Lianoglou mailinglist.honeypot at gmail.com
Fri Feb 3 15:04:19 CET 2012


On Fri, Feb 3, 2012 at 8:00 AM, Johannes Radinger <JRadinger at gmx.at> wrote:
> Hello,
> I tried to use the lapply approach, but I am not sure how to
> se it correctly for my task. Here I just want to give an short
> script which explains how my data structure looks like. It also
> contains the second approach with a for loop which is working but
> there is the question of how assining the result to a list.
> I think the script is somehow self explaining. Anyway what is called
> res is in "reality" rather an object (maxent) than a single value (thats why I need the list)
> #create data
> cat <- c("A","A","B","C","C")
> value <- runif(5)
> df <- data.frame(cat,value)
> # get names of cat with more than 1 entries
> select.cat <- names(table(df$cat)[table(df$cat)>1])
> cat.list <- as.list(select.cat)
> ###### lapply approach ####
> fun = function(x){
>        sub.df<- subset(df,cat ==  x)
>        # here are other operations, result is an object
>        res <- sub.df
>        res #here just a single value but in the long script it is an object
>        }
> reslist <- lapply(cat.list, fun(unlist(cat.list)))

I think you may need to thumb through the ?lapply documentation a bit
more. lapply will feed ever element in the list you are iterating over
into the first argument of the function you have in lapply's second
argument, so you would rather have something like:

reslist <- lapply(cat.list, fun)

Assuming that `fun` only needs one element from cat.list to do its duty ...


Steve Lianoglou
Graduate Student: Computational Systems Biology
 | Memorial Sloan-Kettering Cancer Center
 | Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact

More information about the R-help mailing list