tags:

views:

350

answers:

3

Suppose you're trying to create a data frame within a function. I would like to be able to define the column names ahead of time as one of the parameters of the function. Take the following code:

  foo <- function(a) {
    answer <- data.frame(a=1:5)
    return(answer)
    }

In the above example, I would like to be able to specify the value of the column name in the function foo(), e.g. foo('my.name') so that answer has the column name my.name instead of a. I imagine you could code this up within the function using colnames(), but I was interested in an alternative approach.

+4  A: 

Using colnames is the only way that I'm aware of for a data.frame, although colnames() is itself a vector so there's no need to do any iterating on it. This version handles two columns:

foo <- function(cname) {
   answer <- data.frame(1:5, 1:5)
   colnames(answer) <- cname
   return(answer)
}
> foo(c("a","b"))
  a b
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
Shane
+3  A: 

Here's an alternative using substitute and eval.

foo <- function(var) {
  eval(substitute(data.frame(var = 1:5)), list(var = as.name(var)))
}

I hope you'll agree that the colnames solution is simpler.

hadley
A: 

A minor adjustment to Shane's code, in case you really want to use substitute, or you really can't be bothered to type the extra quotes.

foo <- function(a) {
   answer <- data.frame(1:5)
   colnames(answer) <- as.character(substitute(a))
   answer
}
foo(mycolname)

  mycolname
1         1
2         2
3         3
4         4
5         5
Richie Cotton