[R] idiom for constructing data frame
h.wickham at gmail.com
Fri Apr 3 16:01:38 CEST 2015
On Tue, Mar 31, 2015 at 6:42 PM, Sarah Goslee <sarah.goslee at gmail.com> wrote:
> On Tue, Mar 31, 2015 at 6:35 PM, Richard M. Heiberger <rmh at temple.edu> wrote:
>> I got rid of the extra column.
>> data.frame(r=seq(8), foo=NA, bar=NA, row.names="r")
> After much fussing, including a disturbing detour into nested lapply
> statements from which I barely emerged with my sanity (arguable, I
> suppose), here is a one-liner that creates a data frame of arbitrary
> number of rows given an existing data frame as template for column
> number and name:
> n <- 8
> df1 <- data.frame(A=runif(9), B=runif(9))
> do.call(data.frame, setNames(c(list(seq(n), "r"), as.list(rep(NA,
> ncol(df1)))), c("r", "row.names", colnames(df1))))
> It's not elegant, but it is fairly R-ish. I should probably stop
> hunting for an elegant solution now.
Given a template df, you can create a new df with subsetting:
df2 <- df1[rep(NA_real_, 8), ]
rownames(df2) <- NULL
This has the added benefit of preserving the types.
More information about the R-help