pApaAPPApapapa
pApaAPPApapapa

Reputation: 385

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).

Upvotes: 5

Views: 11476

Answers (2)

Istrel
Istrel

Reputation: 2588

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 
}

Upvotes: 6

statespace
statespace

Reputation: 1664

One way to do this would be to store separately names of all your input vector names and then pass them to assign function. Like assign takes text string for output object name, get looks up object from string.

I will assume your vectors all follow common pattern and start with "d", to make it all as dynamic as possible.

d1 <- c(1,2,3)
d2 <- c(2,3,4)

vec_names <- ls(pattern = "^d")

log_vec <- function(x){
  log(x)
}

sapply(vec_names, function(x) assign(paste0("log.", x), log_vec(get(x)), envir = globalenv()))

This should create two new objects "log.d1" and "log.d2".

Upvotes: 0

Related Questions