[R] Fw: Evaluating strings as variables

Matthias.Kohl@uni-bayreuth.de Matthias.Kohl at uni-bayreuth.de
Sun Jun 20 23:37:43 CEST 2004


> "Robin Gruna" <robin_gruna at hotmail.com> writes:
>
>> I have the following problem: I have a list as follows,
>>
>> > values <- list(red = 1, yellow = 2, blue = 3)
>>
>> > values
>> $red
>> [1] 1
>>
>> $yellow
>> [1] 2
>>
>> $blue
>> [1] 3
>>
>> There is also a vector containing the diffrent "colors" as character
>> strings:
>>
>> > colors <- c("red", "red", "blue", "yellow", "red", "blue")
>> > colors
>> [1] "red"    "red"    "blue"   "yellow" "red"    "blue"
>>
>> Now i can attach the list values to R:
>>
>> > attach(values)
>> > red
>> [1] 1
>>
>> etc...
>>
>> Now to my problem: How can I make R in a simple way to evaluate the
>> strings "red", "blue" etc. as variables, returning their numeric
>> values ? As result I want to get a vector containing the values of the
>> colors like this one:
>>
>> > values.colors
>> [1] 1 1 3 2 1 3
>
> Forget about the attach() business, and do
>
> values <- unlist(values) # or values <- c(red = 1, yellow = 2, blue = 3)
> values.colors <- values[colors]
>
> If you insist on going via variables, try
>
> sapply(colors, get)
>

or?
unlist(mget(colors, envir = as.environment(-1), inherits = TRUE))

Matthias

> --
>    O__  ---- Peter Dalgaard             Blegdamsvej 3
>   c/ /'_ --- Dept. of Biostatistics     2200 Cph. N
>  (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
> ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html




More information about the R-help mailing list