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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With