Reputation: 1159
I am currently looking for a way to combine several tables together which have the same structure and column names. For example, I would like to combine these three tables:
>dt1
user number
A 32
A 33
A 35
A 23
A 32
A 44
A 33
>dt2
user number
B 32
B 33
B 35
B 23
B 32
B 44
B 33
>dt3
user number
C 32
C 33
C 35
C 23
C 32
C 44
C 33
and get:
>dt_combined
user number
A 32
A 33
A 35
A 23
A 32
A 44
A 33
B 32
B 33
B 35
B 23
B 32
B 44
B 33
C 32
C 33
C 35
C 23
C 32
C 44
C 33
I have been trying to use either join or merge, but as simple as this problem is, I can't seem to pinpoint the fast and easy solution within data.table. Would anyone have any suggestions? Thanks!
Upvotes: 0
Views: 116
Reputation: 193687
You've tagged this as data.table
, which has a convenient function rbindlist
.
You can use it in conjunction with mget
, like this:
library(data.table)
rbindlist(mget(ls(pattern = "dt\\d")))
The mget
step creates a list
of the objects in your workspace matching a naming pattern like dt1
, dt2
, and so on (dt
+ "digits"). rbindlist
takes that list and makes it into one big data.table
.
> print(rbindlist(mget(ls(pattern = "dt\\d"))), topn = 3)
user number
1: A 32
2: A 33
3: A 35
---
19: C 32
20: C 44
21: C 33
Upvotes: 3