Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: creating a named vector from variables

Tags:

r

Inside a function I define a bunch of scalar variables like this:

a <- 10
b <- a*100
c <- a + b

At the end of the function, I want to return a,b,c in a named vector, with the same names as the variables, with minimal coding, i.e. I do not want to do:

c( a = a, b = b, c = c )

Is there a language construct that does this? For example, if I simply do return(c(a,b,c)) it returns an unnamed vector, which is not what I want. I currently have a hacky way of doing this:

> cbind(a,b,c)[1,]
   a    b    c 
  10 1000 1010 

Is there perhaps a better, less hacky, way?

like image 824
Prasad Chalasani Avatar asked Feb 18 '11 14:02

Prasad Chalasani


1 Answers

Here's a function to do that for you, which also allows you to optionally name some of the values. There's not much to it, except for the trick to get the unevaluated expression and deparse it into a single character vector.

c2 <- function(...) {
  vals <- c(...)

  if (is.null(names(vals))) {
    missing_names <- rep(TRUE, length(vals))
  } else {
    missing_names <- names(vals) == ""
  }
  if (any(missing_names)) {
    names <- vapply(substitute(list(...))[-1], deparse, character(1))
    names(vals)[missing_names] <- names[missing_names]
  }

  vals
}

a <- 1
b <- 2
c <- 3

c2(a, b, d = c)
# a b d 
# 1 2 3 

Note that it's not guaranteed to produce syntactically valid names. If you want that, apply the make.names function to the names vector.

c2(mean(a,b,c))
# mean(a, b, c) 
#            1 

Also, as with any function that uses substitute, c2 is more suited for interactive use than to be used within another function.

like image 176
hadley Avatar answered Nov 07 '22 20:11

hadley