[R] idiom for constructing data frame

peter dalgaard pdalgd at gmail.com
Fri Apr 3 17:38:41 CEST 2015


> On 03 Apr 2015, at 16:46 , William Dunlap <wdunlap at tibco.com> wrote:
> 
> > 
> > df <- as.data.frame(rep(list(rep(NA_real_, 10)),3))
> > names(df) <- names
> 
> As a matter of personal style (and functional programming
> sensibility), I prefer not to make named objects and then modify them.
> Also, the names coming out of that as.data.frame call are exceedingly
> ugly and I'd rather not generate them at all.
> 

Ah, yes, I missed the generation of intermediate names. You can name the list before as.data.frame, though:

l <- rep(list(rep(NA_real_, 10)),3)
names(l) <- names
as.data.frame(l)

or as a one-liner:

as.data.frame(structure(rep(list(rep(NA_real_, 10)), 3) , .Names=names))

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list