1

I am trying to create a variable inside a function in R, but the name of this variable depends on the parameter of the function, so I want to name it with paste.

I will show what I mean with an example:

variable <- function(name){
assign(paste0("variable_",name),1)
}
variable("one")
variable_one

How should I use the assign command so I can access the variable outside the function? What I mean is that when I use variable_one I get 1 (I know using <<- , but not with assign).
Any help will be appreciated.

Rai
  • 113
  • 12

2 Answers2

2

To change variables outside of the function you need to specify the envir argument to assign.

This will lead to the desired result in your case.

variable <- function(name) {
    assign(paste0("variable_", name), 1, envir = parent.frame())
}

However it is almost always better to use a different solution such as what Ronak Shah suggests, as things can get messy quickly if you fiddle too much with things like these.

Consider (using the above function):

variable_two <- "twenty"
variable("two")

This will overwrite variable_two without a warning, potentially leading to problems further down the line.

moonpainter
  • 76
  • 1
  • 5
1

Do you really need to use assign?

Instead of cluttering your environment with global variables you could return them as list

variable <- function(name){
   setNames(list(1), paste0("variable_", name))
}

variable("two")
#$variable_two
#[1] 1

If you want to make it more general, you could do

variable <- function(name){
   setNames(as.list(rep(1, length(name))), paste0("variable_", name))
}

lst1 <- variable(c("two", "three"))

and then access individual values using [[

lst1[["variable_two"]]
#[1] 1
lst1[["variable_three"]]
#[1] 1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213