5

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

1
  • 4
    Don't do this. The proper way is log.d <- yourfunction(d). Side effects like the one you want are evil and not necessary. Commented Nov 4, 2016 at 9:06

2 Answers 2

6

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 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much. Works like a charm!
@pApaAPPApapapa but beware... my.function(my.function(d)) doesn't return log.log.d as you might hope. This function doesn't play nicely with itself, let alone other functions like lapply.
0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.