[R] Create data frame from header only

Henrik Bengtsson hb at stat.berkeley.edu
Tue Aug 5 03:48:48 CEST 2008


See dataFrame() in R.utils.  It was design for the purpose of
allocating empty data frames in an efficient way.

Example:

> library(R.utils);
> df <- dataFrame(colClasses=c(a="integer", b="double"), nrow=10);
> str(df)
'data.frame':   10 obs. of  2 variables:
 $ a: int  0 0 0 0 0 0 0 0 0 0
 $ b: num  0 0 0 0 0 0 0 0 0 0

/Henrik


On Mon, Aug 4, 2008 at 6:42 PM, Etienne B. Racine <etiennebr at gmail.com> wrote:
>
> Even if it's not so elegant, I will bind it in a function, so I don't have to
> bother with that anymore. I think there should be a simple function in R to
> initialize an empty data frame. From what I've read, it is a recurrent
> question on that list.
>
> #Create an empty data frame from a header list
> empty.df<- function(header){
>        df<-data.frame(matrix(matrix(rep(1,length(header)),1),1))
>        colnames(df)<-header
>        return(df[NULL,])
> }
>
> # Usage
> new.df <- empty.df(paste("A",1:5,sep=""))
>> new.df
> [1] A1 A2 A3 A4 A5
> <0 rows> (or 0-length row.names)
>
> Thanks again,
> Etienne
>
>
> milton ruser wrote:
>>
>> Hi Etienne
>>
>> It is not so elegant, bu I think that work.
>>
>>
>> colname.list<-paste("A",1:5,sep="")
>>
>> df<-data.frame(matrix(matrix(rep(1,length(colname.list)),1),1))
>> df
>> colnames(df)<-colname.list
>> df
>>
>> df<-df[-1,]
>> df
>>
>> Cheers,
>>
>>
>> Miltinho Astronauta
>> Brazil
>>
>
> --
> View this message in context: http://www.nabble.com/Create-data-frame-from-header-only-tp18822575p18823082.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org 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