Wednesday, February 11, 2015

R: Initializing an empty list

If you are new to R, there is a thick chance that you may want to grow your dataset (dataframe) dynamically. As we all in know that dynamic memory allocation is a tricky business and in R it is more so.

In R, dynamically allocated memory in loops and function affects the performance of the system(program). A vector object’s growth in each iteration of a loop takes its own time for the loop to complete, which decreases the program speed.
The best solution to get rid of such speed issues is to predefined size of vector and fill it up with the values inside for loop, whenever possible.

For example:
>emptyData <- rep(NA, 100000)
>emptyData <- rep(1:100)
>emptyData <- rep(1:10, times=3)
Happy programming!

No comments:

Interview Question Preperation : Find longest subarray whose sum is equal to K

Software Engineering Practice interview question Given a array of N elements. Find the length of Longest Subarray whose sum is equal to give...