I’m trying to initialize a data.frame with 2 columns and 40 rows to which I’ll go on adding rows. This is the code that I have –
result.frame = as.data.frame(matrix(ncol=2, nrow=10))
names(result.frame) = c("ID", "Value")
for (i in 1:10) {
value = somefunction(i)
rbind(result.frame, c(i, value))
}
When I run this, I’m just getting a data.frame containing NA. Also, I read on SO that dynamically growing structures is one of the least efficient ways to code in R. If this is true, what is the right way to accomplish something like this?
Thanks a lot!
you aren’t assigning your result frame to anything! The code below does what I think you were trying to show. However as you mention, it is inefficient.
Instead make the data.frame the full size you want and assign into it:
breif timinigs:
Aside from time efficiencies, there are also important memory concerns as data gets larger. To perform the
rbindoperation, the data must be copied which means you need twice the memory in contiguous blocks. Assigning to an already createddata.framedoesn’t have this issue.