Search code examples
rvariablesenvironment-variablesglobal-variables

How to pass on the name of a variable in R


So, I'm making a function like

    example <- function(x, y){
z <- data.frame("variable name" = y, "Quantity of 1" = sum(x==1, na.rm = TRUE))
eval(as.character(y)) <<- z
}

list <- sample(c(0,1), size = 12, replace = TRUE)

If I evaluate my function using

example(list, "list")

It gives me an

error in eval(as.character(y)) <<- z: object 'y' not found

I want the function to give me a variable which I could find by the name I pass on it (as "Y") given that I'll have to work using the same procedures multiples times.


Solution

  • I think you are looking for assign:

    example <- function(x, y){
      z <- data.frame("variable name" = y, "Quantity of 1" = sum(x==1, na.rm = TRUE))
      assign(y, z, envir = parent.frame())
    }
    
    list <- sample(c(0,1), size = 12, replace = TRUE)
    
    example(list, "list")
    
    list
    #>   variable.name Quantity.of.1
    #> 1          list             5
    

    However, please note that this is not a great idea. You should try to avoid writing functions that can over-write objects in the global environment (or other calling frame) as this can have unintended consequences and is not idiomatic R.

    It would be better to have:

    example <- function(x, y){
      data.frame("variable name" = y, "Quantity of 1" = sum(x==1, na.rm = TRUE))
    }
    

    and do

    list <- example(list, "list")
    

    or, better yet:

    example <- function(x){
      data.frame("variable name" = deparse(substitute(x)), 
                 "Quantity of 1" = sum(x==1, na.rm = TRUE))
    }
    

    So you can just do:

    list <- example(list)
    

    Furthermore, it is a good idea to avoid using a common function name like list as a variable name.