[R] how do i use the get function to obtain an element from a list...

Duncan Murdoch murdoch at stats.uwo.ca
Tue Aug 21 21:44:49 CEST 2007


On 8/21/2007 3:35 PM, Juan Manuel Barreneche wrote:
> my problem can be explained with the following example:
> 
> x <- 1:12
> y <- 13:24
> a <- data.frame(x = x, y = y)
> 
> ## if i write
> a$x
> ## it returns
> [1]  1  2  3  4  5  6  7  8  9 10 11 12
> 
> ## but the function get doesn't recognize a$x. Instead it produces the
> following error:
> get("a$x")
> Error in get(x, envir, mode, inherits) : variable "a$x" was not found

a$x is an expression, which you could evaluate, not a variable, which 
you could get.

> 
> i intend to do it inside a loop, using a new object (and hence, a new
> name) for each iteration (i.e., instead of a$x, it would be a$1, a$2,
> a$3, and so on, for a million times).
> 
> i would greatly appreciate it if someone could help me on this issue,

Why name things?  I'd use something like

for (i in 1:1000000) print(a[[i]])

Duncan Murdoch



More information about the R-help mailing list