[R] Adding unequal tables

arun smartpink111 at yahoo.com
Fri Apr 12 15:44:29 CEST 2013


Hi,
table.x<- as.table(as.matrix(read.table(text="
A    B     C    D
2     4      6     5
",sep="",header=TRUE)))
table.y<- as.table(as.matrix(read.table(text="
C  D
5   1
",sep="",header=TRUE))) 
library(plyr)
library(reshape2)
vec1<-rowSums(join(melt(table.x)[,-1], melt(table.y)[,-1],by="Var2")[,-1],na.rm=TRUE)
names(vec1)<- colnames(table.x)
 table.xy<-as.table(vec1)
table.xy
# A  B  C  D 
# 2  4 11  6 

#or
 dat1<-merge(table.x,table.y,all=TRUE)[,-1]
table.xy<-as.table(with(dat1,tapply(Freq,list(Var2),FUN=sum)))
 table.xy
# A  B  C  D 
# 2  4 11  6 
 str(table.xy)
# 'table' int [1:4(1d)] 2 4 11 6
# - attr(*, "dimnames")=List of 1
#  ..$ : chr [1:4] "A" "B" "C" "D"

#or
 datNew<-join(as.data.frame(table.x),as.data.frame(table.y),type="full")[,-1]
res<-aggregate(Freq~Var2,data=datNew,sum)[,2]
 names(res)<- colnames(table.x)
 table.xy<-as.table(res)
table.xy
# A  B  C  D 
# 2  4 11  6 
A.K.


>This is probably really simple, but I'm missing something: 

>I have two tables generated with the table() function that have 
overlapping columns. I want to add the entries where the column is the 
same. For >instance: 

>table.x 
>A    B     C    D 
>2     4      6     5 
>
>table.y 
>
>C  D 
>5   1 
>
>Output needed: 
>A   B   C    D 
>2    4    11  6



More information about the R-help mailing list