Home > Back-end >  Getting the name of the vector passed to a function in R
Getting the name of the vector passed to a function in R

Time:12-15

I think this best described by example. I have a function that does something and then returns a list. I want to be able to use the name of the variable that was passed to the function as the name of an element in the list that is to be returned. For example, my function is

myFun <- function(x) {  
      ... do something here to generate some value  
    list(original name of x =  some value)   
}  

CL <- c(1,2,3,4,5)  
z <- myFun(CL)

I am passing CL to the function. Then I want the function to return the following:

z
$CL
[1] some value

How can I get that variable name CL from the pass?

CodePudding user response:

Here an example that takes a value (x) and adds 2 to it, returning inside a list with name of the object passed to the function (myFUN).

myFUN <- function(x){
  
  y <- x   2
  
  output <- list(y)
  
  names(output) <- deparse(substitute(x))
  
  return(output)
}

CL <- 3

myFUN(CL)

$CL
[1] 5
  • Related