Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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.

like image 771
andrewj Avatar asked Dec 14 '22 01:12

andrewj


2 Answers

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
like image 89
Shane Avatar answered Jan 18 '23 23:01

Shane


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.

like image 38
hadley Avatar answered Jan 19 '23 00:01

hadley