pApaAPPApapapa pApaAPPApapapa - 2 months ago 46
R Question

Dynamic variable names in function in R

I am looking to make a function that takes a vector as input, does some simple arithmetic with the vector and call the new vector something which consists of a set string (say, "log.") plus the original vector name.

d = c(1 2, 3)
my.function <- function { x
x2 <- log(x)

I would like the function to return a vector called log.d (that is, not log.x or something set, but something dependent on the name of the vector input as x).


You can try next:

d = c(1, 2, 3)

my.function <- function(x){
    x2 <- log(x)

    arg_name <- deparse(substitute(x)) # Get argument name
    var_name <- paste("log", arg_name, sep="_") # Construct the name
    assign(var_name, x2, env=.GlobalEnv) # Assign values to variable
    # variable will be created in .GlobalEnv