0

I want to map variable to a number as shown in the list below through a function.

x <- list(
  a = 1,
  b = 2, 
  c = 3
)

x$a
[1] 1

I need to use this mapping at different places inside a script so I want to use a function that returns the number if I pass in the variable. However, if I make a function as shown below it does not work. Not sure what I am missing.

get_x <- function(var) {
  x <- list(
    a = 1,
    b = 2, 
    c = 3
  )
  return(x$var)
}

get_x(a)
NULL

Coming form python background so this seems a logical way to do it.

  • 1
    Change the last line to `return(x[[var]])` and call it as `get_x('a')` – Ronak Shah Sep 11 '20 at 00:09
  • The duplicate talks about data.frames, but data.frames are just fancy lists so the same rules about using variables with `$` applies. Though it seems somewhat inefficient to keep recreating the list just to extract a single element each time. What exactly do you plan to do with this function? – MrFlick Sep 11 '20 at 00:13

0 Answers0