R - use rbind on multiple variables with similar names

匆匆过客 提交于 2019-11-26 22:57:04

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

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!