[R] how to optionally include variables in a data.frame at assignment

Gabor Grothendieck ggrothendieck at gmail.com
Thu Jun 14 01:49:00 CEST 2007


How about this:

data.frame2 <- function(...) {
	L <- list(...)
	as.data.frame(L[!sapply(L, is.null)])
}

# test 1
include <- FALSE
data.frame2(a = 1:3, junk = if (include) z, b = 3:1)

# test 2
z <- letters[1:3]
include <- TRUE
data.frame2(a = 1:3, junk = if (include) z, b = 3:1)


On 6/13/07, Jenny Bryan <jenny at stat.ubc.ca> wrote:
> I am creating a data.frame inside a function and the set of variables
> to include depends on the current value of other variables.  Is there
> a way to accomplish this in the original assignment?  Or must I first
> create the core data.frame with the variables I always want and then
> use if blocks to add other variables?
>
> Basically, I'm hoping for something like this (which does not work):
>
> newDat <- data.frame(x, y, if(zInclude) z else NULL)
>
> Thanks, Jenny
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list