r - Dynamically allocate a data.frame with grace -


i have data frame supposed grow (adding rows) during runtime. wise pre-allocate data frame beforehand (cmp. the r inferno). pre-allocation routine should accept kinds of data frame composition (i.e. number of columns , column classes).

example

arbitrarydf<-function(){     return(data.frame(c="char",l=true,n=4.5,stringsasfactors=false)) } 

returns arbitrary data frame use template. need n <- 10 rows, might do:

data<-as.data.frame(lapply(arbitrarydf(),function(x){eval(parse(text=paste(class(x),"(",n,")")))}),stringsasfactors=false) 

which returns 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 say, use of eval() ugly. there more straightforward solution this?

as said, routine needs accept data frame composition, otherwise @mnel's answer enough.

update

essentially, achieve same

data <- data.frame(x= numeric(n), y= integer(n), z = character(n))  

but in generic way, df layout. info of df layout should drawn given df (here arbitrarydf())

to sort of generalize simon's comment, perhaps of use you:

myfun <- function(sourcedf, length) {   classes <- sapply(sourcedf, class)   data.frame(lapply(classes, vector, length = length)) } 

here, first extract classes of each column of source data.frame , use template new data.frame, length determined length argument.

example:

myfun(arbitrarydf(), 5) #   c     l n # 1   false 0 # 2   false 0 # 3   false 0 # 4   false 0 # 5   false 0 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -