[R] assigning a list item using a variable for a name

Joshua Wiley jwiley.psych at gmail.com
Wed Mar 23 03:14:47 CET 2011


Hi RSVP,

On Tue, Mar 22, 2011 at 4:47 PM, RSVP <paul at ptrow.com> wrote:
> I have a list.
>
> my.list <- list(Tom=c(1,2,3), Dick=c(4,5,6), Harry=c(7,8,9))
>
> I assign one of the names of the list to a variable.
>
> name <- "Harry"
>
> I can access the value of the list using the variable as follows:
>
>  eval(parse(text=paste("my.list$", name, sep="")))

Woah, you don't want to do things that way.  The evil trio (eval,
parse, paste) only leads to pain (and we're not just talking early
grey hairs).

There is another extraction operator you should familiarize yourself
with.  "[" and similarly, "[[" (see ?"[[" for documentation).  Try
this then:

my.list <- list(Tom=c(1,2,3), Dick=c(4,5,6), Harry=c(7,8,9))
myname <- "Harry"
my.list[[myname]]  ## extract

my.list[[myname]] <- 11:13 ## assign
my.list[[myname]] ## extract

HTH,

Josh
>
> [1] 7 8 9
>
> But how do I change the value of my.list$Harry using the variable name? This
> doesn't work:
>
>  eval(parse(text=paste("my.list$", name, sep=""))) <- c(1,4,7)
>
> Error in eval(parse(text = paste("my.list$", name, sep = ""))) <- c(1,  :
>  target of assignment expands to non-language object
>
> The following only replaces the first element of my.list$Harry
>
>  my.list[name] <- c(1,4,7)
> Warning message:
> In my.list[name] <- c(1, 4, 7) :
>  number of items to replace is not a multiple of replacement length
>
>> my.list[name]
> $Harry
> [1] 1
>
> Any suggestions?
>
> Thanks.
>
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/assigning-a-list-item-using-a-variable-for-a-name-tp3398084p3398084.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list