1

How do I create a variable from function input? For example,

test <- function(var_name, num) {
    var_name <<- 2 + num
}
test(hello, 2)

so hello will then be 4?

2
  • 1
    Not clear what you are asking. Waht is your expected result? Commented Jun 26, 2017 at 21:49
  • 5
    Functions in R are not meant to alter variables values outside their own scope. This is not a good design for R. Function should return values that you assign to variables; more like hello <- test(2) Commented Jun 26, 2017 at 21:56

1 Answer 1

2

I think what you want is something like this:

test <- function(var_name, num) {
    assign(var_name, num + 2, envir = .GlobalEnv)
}

test("hello", 2)

Here assign creates the varible var_name in the gobal environment (you need to set the envir parameter to .GlobalEnv to do that). Notice that the var_name parameter should be a string.

Sign up to request clarification or add additional context in comments.

1 Comment

or if you insist on test(hello,2) you can use assign(deparse(substitute(var)), num+2, envir=.GlobalEnv) -- but please see @MrFlick's comment above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.