How to merge tables in R?

temp<-merge(a,b,by='Var1')
temp$sum<-temp$Freq.x + temp$Freq.y

   Var1 Freq.x Freq.y sum
1     3     26      1  27
2   3.3      6      2   8
3   3.5      6      2   8
4   3.6      4      1   5
5   3.7      3      1   4
6   3.8      6      1   7
7   3.9      2      3   5
8     4      1      5   6
9   4.1      1      3   4
10  4.2      1      4   5
11  4.4      1      4   5

This will work if you want to use the variables which are present in both a and b:

n <- intersect(names(a), names(b))
a[n] + b[n]

#  3 3.3 3.5 3.6 3.7 3.8 3.9   4 4.1 4.2 4.4 
# 27   8   8   5   4   7   5   6   4   5   5

If you want to use all variables:

n <- intersect(names(a), names(b)) 

res <- c(a[!(names(a) %in% n)], b[!(names(b) %in% n)], a[n] + b[n])

res[order(names(res))] # sort the results

Here is another one:

transform(merge(a,b, by="Var1"), sum=Freq.x + Freq.y)
   Var1 Freq.x Freq.y sum
1     3     26      1  27
2   3.3      6      2   8
3   3.5      6      2   8
4   3.6      4      1   5
5   3.7      3      1   4
6   3.8      6      1   7
7   3.9      2      3   5
8     4      1      5   6
9   4.1      1      3   4
10  4.2      1      4   5
11  4.4      1      4   5

Tags:

Merge

R