5

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?

2 Answers 2

14

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) )
Sign up to request clarification or add additional context in comments.

2 Comments

This works, but only if I don't have other variables with the same pattern. For example, if, in my original code, I now set the for loop to go up to 1000, then set it to go back to 10, the do.matrix variable will have way too many rows.
Thanks, @DWin. Your followup to my comment was correct. I apologize. And thanks for this additional line of code. This is what I needed.
2

I would like to add another way to merge multiple dataframes with dynamic names. This will be accomplished by using mget and bind_rows from dplyr.

# 3 Data frames are created
TXN_MONTH_01 <- data.frame(a = 1:10, b = 101:110)

TXN_MONTH_02 <- data.frame(a = 11:20, b = 111:120)

TXN_MONTH_03 <- data.frame(a = 21:30, b = 121:130)

#create a list using dynamic names of dataframes
z <- as.list(mget(paste("TXN_MONTH_0", 1:3, sep="")))
library(dplyr)
#now call bind rows
bind_rows(z)
#    a   b
#1   1 101
#2   2 102
#3   3 103
#4   4 104
#5   5 105
#.....
#.....
#25 25 125
#26 26 126
#27 27 127
#28 28 128
#29 29 129
#30 30 130

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.