Skip to content

assign a list using expression?

6 messages · Skotara, Patrick Burns, Gabor Grothendieck +1 more

#
Dear R-users,

I would like to assign elements to a list in the following manner:
mylist <- list(a = a, b = b, c = c)

To do this I tried
myexpr <- expression(a = a, b = b, c = c)
mylist <- list( eval(myexpr) )

It ends up by overwriting a when b is assigned and b when c is assigned. 
Additionally the element of the list does not have a name.
Could you tell me why this is the case?
Thank you very much in advance!

Best regards,
Nils
#
I think this is glossing over 9.7 of 'The R Inferno'.
You aren't telling us what you really want to achieve.
It seems hard for me to believe that the approach
you are taking is going to be the easiest route to
whatever that is.

Patrick Burns
patrick at burns-stat.com
+44 (0)20 8525 0696
http://www.burns-stat.com
(home of "The R Inferno" and "A Guide for the Unwilling S User")
Skotara wrote:
#
The purpose of this is not clear but depending on what a and b are you
might be able to use a data frame (which is a list):
a b
1 1 3
2 2 4
On Mon, Jan 12, 2009 at 9:42 AM, Skotara <nils.skotara at uni-hamburg.de> wrote:
#
Thank you Patrick and Gabor!
Sorry, I think I have not explainend it well.
The purpose is as follows:
    names <- letters[1:3]
    values <- data.frame(a = 1:3, b = 4:6, c = 7:9)
With more complicated objects similar to 'names' and 'values' I wrote 
the following line to assign the elements of the list:
    mycommand <- parse(text = paste(names, " = values[\"", names, "\"]", 
sep="") )
However,
    list(eval(mycommand))
does not do what I want.
whereas
    list(a = values["a"], b = values["b"], c = values["c"])
does.

I can not tell why...
I try to understand, what expression and eval do. I know that many times 
there are other ways to achieve the same goal.
So here, too. But I think there should be a reason why it does not work 
that way.

Best regards!
Nils
#
This still isn't clear.  In your post, values is already
a list with the required names and values in it so the
whole exercise is pointless -- you are starting
out with the answer.

Just guessing, but maybe your setup is a set of variables
in your workspace and a vector of their names with the
output being a named list of them:

a <- 1:2; b <- 1:3
nms <- c("a", "b")
sapply(nms, get, simplify = FALSE)
On Mon, Jan 12, 2009 at 10:58 AM, Skotara <nils.skotara at uni-hamburg.de> wrote: