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.
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).
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With