I have many variables that I have created using code like this:
for (i in 1:10) {
assign(paste0("variable", i), i )}
I now need to use rbind on the variables to combine them. I tried something like this to no avail:
rbind(assign(paste0("variable", 1:10)))
Any suggestions on what to do?
The rbind() function in R and the bind_rows() function are the most useful functions when it comes to data manipulation. You can easily bind two data frames of the same column count using rbind() function.
Rbind as is only accepts two dataframes, so we have to adjust our code slightly to accommodate for more dataframes.
The function rbind() is slow, particularly as the data frame gets bigger. You should never use it in a loop. The right way to do it is to initialize the output object at its final size right from the start and then simply fill it in with each turn of the loop.
rbind() throws an error whereas bind_rows assigns “NA” to those rows of columns missing in one of the data frames where the value is not provided by the data frames.
That is the wrong way to handle related items. Better to use a list or dataframe, but you will probably find out why in due course. For now:
do.matrix <- do.call(rbind, lapply( ls(patt="variable"), get) )
Or:
do.matrix <- do.call(rbind, lapply( paste0("variable", 1:10) , get) )
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