[R] Combining two tables without going through lot of ifelse statement

arun smartpink111 at yahoo.com
Fri Aug 23 15:45:05 CEST 2013



In the case of ?data.table()

dt1<-data.table(rbind(as.matrix(dat1),as.matrix(dat2))) ## converted the data.frame to matrix to mimic the situation

 dt2<- subset(dt1[,sum(V2),by=V1],V1!=0)
 setnames(dt2,2,"V2")
 dt2
#   V1 V2
#1:  1 10
#2:  3 10
#3:  2 10


#or

 res<-with(as.data.frame(rbind(as.matrix(dat1),as.matrix(dat2))),aggregate(V2~V1,FUN=sum))
 res1<- res[res[,1]!=0,]
 res1
#  V1 V2
#2  1 10
#3  2 10
#4  3 10
A.K.
________________________________
From: Anindya Sankar Dey <anindya55 at gmail.com>
To: arun <smartpink111 at yahoo.com> 
Sent: Friday, August 23, 2013 9:40 AM
Subject: Re: [R] Combining two tables without going through lot of ifelse statement



Mine is matrices, will this work on matrices as well?

Thank for your help



On Fri, Aug 23, 2013 at 7:02 PM, arun <smartpink111 at yahoo.com> wrote:

However it is not clear when you mention these are tables.  There is ?table() and ?data.frame and the structure will be different in each case.  Here, I assumed that your table is data.frame..
>
>
>
>
>----- Original Message -----
>From: arun <smartpink111 at yahoo.com>
>To: Anindya Sankar Dey <anindya55 at gmail.com>
>Cc: R help <r-help at r-project.org>
>Sent: Friday, August 23, 2013 9:30 AM
>Subject: Re: [R] Combining two tables without going through lot of ifelse       statement
>
>Hi,
>Try:
>
>dat1<- read.table(text="
>1 10
>3  5
>0  0
>",sep="",header=FALSE)
>dat2<- read.table(text="
>2 10
>0  0
>3  5
>",sep="",header=FALSE)
>res<-with(rbind(dat1,dat2),aggregate(V2~V1,FUN=sum))
>res1<-res[res[,1]!=0,]
> res1
>#  V1 V2
>#2  1 10
>#3  2 10
>#4  3 10
>
>#or
>library(data.table)
>dt1<- data.table(rbind(dat1,dat2))
> dt2<-subset(dt1[,sum(V2),by=V1],V1!=0)
> setnames(dt2,2,"V2")
> dt2
>#   V1 V2
>#1:  1 10
>#2:  3 10
>#3:  2 10
>
>A.K.
>
>----- Original Message -----
>From: Anindya Sankar Dey <anindya55 at gmail.com>
>To: r-help <r-help at r-project.org>
>Cc:
>Sent: Friday, August 23, 2013 8:59 AM
>Subject: [R] Combining two tables without going through lot of ifelse    statement
>
>HI All,
>
>Suppose I have two table like below
>
>Table 1:
>
>1 10
>3  5
>0  0
>
>Table 2:
>
>2 10
>0  0
>3  5
>
>
>I need to create a new table like below
>
>Table 3:
>
>1 10
>2 10
>3 10
>
>The row may interchange in table 3, but is there any way to do this instead
>of writing lot of if-else and loops?
>
>Thanks in advance.
>
>--
>Anindya Sankar Dey
>
>    [[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.
>
>


-- 
Anindya Sankar Dey



More information about the R-help mailing list