andrewj
andrewj

Reputation: 3035

specifying column names of a data frame within a function ahead of time

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.

Upvotes: 4

Views: 9813

Answers (4)

IRTFM
IRTFM

Reputation: 263342

The setNames function will suffice:

> foo <- function(a,nm) {
+     answer <- data.frame(a=1:5)
+     setNames(answer, nm)
+     }
> foo(1:10, 'bar')
  bar
1   1
2   2
3   3
4   4
5   5

Upvotes: 1

Richie Cotton
Richie Cotton

Reputation: 121077

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

Upvotes: 1

hadley
hadley

Reputation: 103898

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.

Upvotes: 4

Shane
Shane

Reputation: 100174

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

Upvotes: 7

Related Questions