With the column names of the data frame in the function in advance

Suppose you are trying to create a data frame inside a function. I would like to be able to predefine the column names as one of the function parameters. Take the following code:

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

In the above example, I would like to specify the value of the column name in the foo() function, for example. foo('my.name') so that the response has the column name my.name instead of a . I suppose you could code this in a function using colnames() , but I was interested in an alternative approach.

+4
source share
4 answers

Using colnames is the only way I know for data.frame, although colnames () is itself a vector, so there is no need to do any repetitions 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")) ab 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 
+7
source

An alternative using substitute and eval .

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

I hope you agree that the colnames solution colnames simpler.

+4
source

A small adjustment to Shane's code if you really want to use substitute , or you really have nothing to worry about entering 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 
+1
source

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 
+1
source

All Articles