Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a data frame in R in a loop

Tags:

dataframe

r

I am trying to populate a data frame from within a for loop in R. The names of the columns are generated dynamically within the loop and the value of some of the loop variables is used as the values while populating the data frame. For instance the name of the current column could be some variable name as a string in the loop, and the column can take the value of the current iterator as its value in the data frame.

I tried to create an empty data frame outside the loop, like this

d = data.frame() 

But I cant really do anything with it, the moment I try to populate it, I run into an error

 d[1] = c(1,2) Error in `[<-.data.frame`(`*tmp*`, 1, value = c(1, 2)) :    replacement has 2 rows, data has 0 

What may be a good way to achieve what I am looking to do. Please let me know if I wasnt clear.

like image 894
ganesh reddy Avatar asked Nov 18 '12 17:11

ganesh reddy


People also ask

How do I populate an empty Dataframe in R?

One simple approach to creating an empty DataFrame in the R programming language is by using data. frame() method without any params. This creates an R DataFrame without rows and columns (0 rows and 0 columns).


1 Answers

You could do it like this:

 iterations = 10  variables = 2   output <- matrix(ncol=variables, nrow=iterations)   for(i in 1:iterations){   output[i,] <- runif(2)   }   output 

and then turn it into a data.frame

 output <- data.frame(output)  class(output) 

what this does:

  1. create a matrix with rows and columns according to the expected growth
  2. insert 2 random numbers into the matrix
  3. convert this into a dataframe after the loop has finished.
like image 127
Seb Avatar answered Sep 24 '22 16:09

Seb