Skip to content
Prev 314249 / 398506 Next

how to get a value from a list (using paste function)?

Here are a few examples of eval(parse(text=paste())) failing:
  > cvtest <- list("Test-1"=1, Bozo=2, "Joe's Test"=3)
  >
  > lambda.rule <- "Test-1"
  > eval(parse(text=paste0("cvtest$", lambda.rule))) # want 1
  [1] 0
  > 
  > lambda.rule <- "Joe's Test"
  > eval(parse(text=paste0("cvtest$", lambda.rule))) # want 3
  Error in parse(text = paste0("cvtest$", lambda.rule)) : 
    <text>:1:11: unexpected INCOMPLETE_STRING
  1: cvtest$Joe's Test
             ^

and here is an example of "$" giving a suboptimal result:
  > cvtest$B # want NULL (there is no component named "B")
  [1] 2

"[[" gives the correct result in all cases:
  > lambda.rule <- "Test-1"
  > cvtest[[lambda.rule]]
  [1] 1
  > lambda.rule <- "B"
  > cvtest[[lambda.rule]]
  NULL
  > lambda.rule <- "Bozo"
  > cvtest[[lambda.rule]]
  [1] 2
  > lambda.rule <- "Joe's Test"
  > cvtest[[lambda.rule]]
  [1] 3

Also, I find it hard to read code involving eval(parse(text=paste(...))).

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com