Home > Blockchain >  Is there a way to generate a function where the object name changes with the input of the function?
Is there a way to generate a function where the object name changes with the input of the function?

Time:12-31

Something as such:

gen_sigma <- function(i) {
  sigma_`i` <- matrix(c(1, i, i, 1), nrow = 2, byrow = TRUE)
}

CodePudding user response:

The 'right' thing to do is to use a list as follows, rather than polluting your environment with lots of variable names. This is an example:

n = 10

res_list = vector(length = n, mode = 'list')

for (i in 1:n) {
    res_list[[i]] = matrix(c(1, i, i, 1), nrow = 2, byrow = TRUE)
}

or using lapply

n = 10
res_list = lapply(1:n, function(x) matrix(c(1, x, x, 1), nrow = 2, byrow = TRUE))

One other option is to use assign and get, although I would hope there is a cleaner solution than this, as using these functions is often a bit of a code-smell. I think putting it into a list would likely be the best solution.

gen_sigma <- function(i) {
    output_name = paste0("sigma_", i)
    assign(output_name, matrix(c(1, i, i, 1), nrow = 2, byrow = TRUE), envir=parent.frame())
    get(output_name)
}
gen_sigma(5)
> sigma_5
     [,1] [,2]
[1,]    1    5
[2,]    5    1
  •  Tags:  
  • r
  • Related