开发者

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.


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


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.


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜