R - use rbind on multiple variables with similar n

2019-01-07 21:44发布

问题:

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?

回答1:

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) )


回答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


标签: r rbind