Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - use rbind on multiple variables with similar names

Tags:

r

rbind

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?

like image 906
bill999 Avatar asked Sep 29 '13 03:09

bill999


People also ask

Can you use Rbind for multiple data frames?

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.

Can you Rbind 3 data frames?

Rbind as is only accepts two dataframes, so we have to adjust our code slightly to accommodate for more dataframes.

Is Rbind slow in R?

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.

What is the difference between Rbind and Bind_rows?

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.


1 Answers

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) )
like image 123
IRTFM Avatar answered Nov 15 '22 06:11

IRTFM