[R] dynamically extract data from a list

Gabor Grothendieck ggrothendieck at gmail.com
Tue Aug 12 04:08:23 CEST 2008


Try this:

> e <- expression(Sepal.Width > 4)
> subset(iris, eval(e), select = "Sepal.Length")
   Sepal.Length
16          5.7
33          5.2
34          5.5
> subset(iris, eval(e))
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
16          5.7         4.4          1.5         0.4  setosa
33          5.2         4.1          1.5         0.1  setosa
34          5.5         4.2          1.4         0.2  setosa


On Mon, Aug 11, 2008 at 9:36 PM, Dries Knapen <dries.knapen at gmail.com> wrote:
> Hi,
>
> Based on user input, I wrote a function that creates a list which looks
> like:
>
>> str(list)
> List of 4
>  $ varieties: chr [1:12] "temp.26_time.5dagen_biorep.1"
> "time.5dagen_temp.26_biorep.2" "temp.18_time.5dagen_biorep.1"
> "temp.18_time.5dagen_biorep.2" ...
>  $ temp     : Factor w/ 2 levels "18","26": 2 2 1 1 2 2 1 1 1 1 ...
>  $ time     : Factor w/ 3 levels "14dagen","28dagen",..: 3 3 3 3 1 1 1 1 2 2
> ...
>  $ biorep   : Factor w/ 2 levels "1","2": 1 2 1 2 1 2 1 2 1 2 ...
>
> Now, based on user input as well, I want to dynamically extract data from
> list$varieties. Therefore, I wrote a function which generates a string
> containing the data extraction conditions which looks like this:
>
>> query <- make.contrast.substring(negative.contrast, list)
> Read 1 item
> [1]
> "(list$temp=='18')&(list$time=='14dagen'|list$time=='28dagen'|list$time=='5dagen')&(list$biorep=='1'|list$biorep=='2')"
>
> Now what I want to achieve is to extract data by doing:
>
> list$varieties[query]
>
> which doesn't work since "query" is a string and object names are not
> expanded...
>
> Obviously, manually copying the string like so
>
> list$varieties[(list$temp=='18')&(list$time=='14dagen'|list$time=='28dagen'|list$time=='5dagen')&(list$biorep=='1'|list$biorep=='2')]
>
> works perfectly - but I need it to be automated.
>
> I'm quite new to R and used to programming in PHP, so I may just be
> "conceptually" confused about how to do this. Any help would be greatly
> appreciated.
>
> thanks in advance,
> Dries Knapen
>
>
>
> ********************************************
> Dr. Dries Knapen
>
> University of Antwerp
> Department of Biology
> Ecophysiology, Biochemistry and Toxicology
> Groenenborgerlaan 171 - U711, B-2020 Antwerp
> Belgium
>
> tel ++32 3 265 33 49
> fax ++32 3 265 34 97
>
> ______________________________________________
> 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