[R] From Strings to Variable name. When get does not work

Greg Snow 538280 at gmail.com
Wed Mar 12 20:31:19 CET 2014


You can use get to grab the object, then subset it:

> test <- list(a=2)
> get('test')[['a']]
[1] 2

This way you can even have the variable names in other variables:

> whichvar <- 'a'
> whichlist <- 'test'
> get(whichlist)[[whichvar]]
[1] 2

Even better would be to have any lists that you want to "get" in an
array or environment rather than just sitting in the global
environment so that you can access them using [[]] rather than needing
the get function.

If you have nested arrays (your syntax with multiple $) then you can
just create a vector with the path you want to follow:

> test2 <- list( a=list(b=list(c=5)) )
> whichvars <- c('a','b','c')
> test2[[whichvars]]
[1] 5


The reason you received an error is that "get" takes it argument
literally (does not parse), so it was looking for a variable named
`test$a` rather than the component named "a" in the variable named
"test" which is how it is parsed from the command line.

On Wed, Mar 12, 2014 at 1:42 AM, Alaios <alaios at yahoo.com> wrote:
> Hi all,
> I would like to turn some long strings like MyString$Myfield$MySubfield into variables but it looks like that the get does not like lists
>
>
>
> so for example:
>
>  test<-list(a=2)
>
> test
>>$a
> [1] 2
>
>
> get("test")
>>$a
> [1] 2
>
>
> get("test$a")
>>Fehler in get("test$a") : Objekt 'test$a' nicht gefunden
>
> lapply(test,function(x) return (x$a))
>>Fehler in x$a : $ operator is invalid for atomic vectors
>
> What should I do to read those lists I have as strings?
>
> I would like to thank you in advance for your reply
>
> regards
> A
>
>         [[alternative HTML version deleted]]
>
>
> ______________________________________________
> 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.
>



-- 
Gregory (Greg) L. Snow Ph.D.
538280 at gmail.com




More information about the R-help mailing list