Home > OS >  Export variable that is named via another variable out of a function
Export variable that is named via another variable out of a function

Time:01-21

Given this sample code,

gene_expression<-function(gene) {
assign((paste0(gene,"_graph")),5)
}

an input of "ACTB" should create a variable that is named "ACTB_graph" and have a value of 5. I would like to be able to export this variable and value out of the function to store for later analysis.

I've tried various permutations of the global operator (<<-) but can't seem to figure it out!

CodePudding user response:

When using assign in a user-defined function, you need to add envr = .GlobalEnv. (Also, need to adjust your parentheses)

gene_expression <- function(gene) {
  assign(paste0(gene,"_graph"), 5, envir = .GlobalEnv)
}

gene_expression("ACTB")

This will store it as an object in the global environment, just like ACTB_graph <- 5 would do.

  •  Tags:  
  • r
  • Related