简体   繁体   中英

Use argument value as variable name in R during function run

How can I create a variable with a name identical to the character value of an argument that I passed to the function ? The following lines doesn't work. Do I have to text an expression with a combination of paste0(), parse() first, and eventually evaluate it with eval()?

f <- function(Argument.to.carry.the.value.that.I.want.to.use.as.name.of.variable.to.be.created){

as.name(Argument.to.carry.the.value.that.I.want.to.use.as.name.of.variable.to.be.created)=my.gene.list

}

f(the.name)

Bests,

Allen Chiu

PS: What I really want to do is to create a global variable during the function run, like:

de.limma=function(path_name){

      ……………

.GlobalEnv$”as indicated by the path_name argument”=de_gene_list

}

This is FAQ 7.21.

The most important part of that answer is where it says not to do this. Global variables are dangerous and can lead to hard to find bugs.

If you need to store a variable so that other functions can find it (common reason people use globals) then it can be cleaner to create a special environment that all the functions can refer to:

mynewenv <- new.env()

fun1 <- function(name) {
  mynewenv[[name]] <- "testing"
}

fun2 <- function(name) {
  print( mynewenv[[name]] )
}

您可以将分配与envir = .GlobalEnv一起使用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM