R - use rbind on multiple variables with similar names

给你一囗甜甜゛ 提交于 2019-11-26 08:28:28

问题


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


来源:https://stackoverflow.com/questions/19074159/r-use-rbind-on-multiple-variables-with-similar-names

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