jonathan
jonathan

Reputation: 149

Concatenate several tables in R

I have 5 data.frames with 10 rows, which correspond to 10 politicians. I use table() to count all the political groups in each data.frame.

So I get 10 tables like this :

grpol.1 <- table(df1$group_pol)
grpol.1
  NI RRDP  SRC  UDI  UMP 
  1    2   3    3    1 
grpol.2
  RRDP  UDI  ECOLO 
  5       4      1 

Now, I would like to concatenate (by column) all of these tables into just one data.frame. There are 7 political groups in all. Note all these tables do not have the same number of columns.

I would like to obtain something like:

 group_pol  grpol.1  grpol.2  ... grpol.5
1 NI              1        0
2 RRDP            2        5
3 SRC             3        0
4 UDI             3        4 
5 UMP             1        0
6 GDR             0        0
7 ECOLO           0        1

Normally, in this case, I would use merging. However it seems impossible to convert tables to data.frames in order to merge. So, what is the alternative to concatenate tables which do not have similar columns ?

Thanks for help,

Upvotes: 2

Views: 3988

Answers (1)

Backlin
Backlin

Reputation: 14842

I'll start by making some example data

grpol.1 <- as.table(c(a=1,b=2, d=3, g=4))
grpol.2 <- as.table(c(b=1, c=2, e=3, f=4))
grpol.3 <- as.table(c(b=198, d=281, e=-12, g=612))

The primitive way of solving it would be

merge(as.data.frame(grpol.1),
      merge(as.data.frame(grpol.2),
            as.data.frame(grpol.3), by="Var1", all=TRUE),
      by="Var1", all=TRUE)

Giving you the following output

  Var1 Freq Freq.x Freq.y
1    a    1     NA     NA
2    b    2      1    198
3    d    3     NA    281
4    g    4     NA    612
5    c   NA      2     NA
6    e   NA      3    -12
7    f   NA      4     NA

However, if you have a lot of tables it is better to keep them in a list so you don't need to write out all their names every time you want to access them.

l <- list(grpol.1, grpol.2, grpol.3)
l <- lapply(l, as.data.frame)
f <- function(x, y) merge(x, y, by="Var1", all=TRUE)
Reduce(f, l)

This is especially important if you want you code to work with an arbitrary number of tables. The next time you run your code you might have 6 tables instead of 5, who knows?

Upvotes: 4

Related Questions