How to create a function that takes a character vector of object names as an argument

I want to create a function that takes a character vector as an argument and do something with R objects that have elements of this character vector as their names. For example, let's say I have three numeric R objects defined in the global environment: x, y, and z. I want to create a unary function that takes c("x", "y", "z") as an argument and returns the result of (x + y) * z.

How can I do this?

# c("x", "y", "z") as an argument and returns the result of (x + y) * z.
x<-1
y<-2
z<-3

add_mult <- function(cv){
  if (length(cv)!=3)
    stop("function undefined for character vector length different from 3")
  (get(cv[1]) + get(cv[2]) )* get(cv[3])
}

add_mult(c("x","y","z"))
#9
1 Like

Don't call get multiple times, use mget:

values <- mget(c("x", "y", "z"))
(values[[1]] + values[[2]]) * values[[3]]
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.