I have a data frame supposed to grow (adding rows) during runtime. It is wise to pre-allocate the data frame beforehand (cmp. The R Inferno). The pre-allocation routine should accept all kinds of data frame composition (i.e. number of columns and column classes).
Example
arbitraryDf<-function(){
return(data.frame(C="char",L=TRUE,N=4.5,stringsAsFactors=FALSE))
}
returns an arbitrary data frame to use as template. I will need N <- 10
rows, so I might do:
data<-as.data.frame(lapply(arbitraryDf(),function(x){eval(parse(text=paste(class(x),"(",N,")")))}),stringsAsFactors=FALSE)
which returns the desired data frame.
>data
C L N
1 FALSE 0
2 FALSE 0
3 FALSE 0
4 FALSE 0
5 FALSE 0
6 FALSE 0
7 FALSE 0
8 FALSE 0
9 FALSE 0
10 FALSE 0
>sapply(data,class)
C L N
"character" "logical" "numeric"
Needless to say, the use of eval()
is ugly. Is there a more straightforward solution to this?
As said, the routine needs to accept any data frame composition, otherwise @mnel's answer was good enough.
Update
Essentially, I would like to achieve the same as
data <- data.frame(x= numeric(N), y= integer(N), z = character(N))
but in a generic way, for any df layout. The info of the df layout should be drawn from a given df (here arbitraryDf())