Message-ID: <49A6E151.9000802@comcast.net>
Date: 2009-02-26T18:37:05Z
From: Marc Schwartz
Subject: Merge question
In-Reply-To: <3B95C29A9AFAF54BA2212277976B28911646EA377A@PEPWMV00073.corp.pep.pvt>
on 02/26/2009 11:52 AM Vadlamani, Subrahmanyam {FLNA} wrote:
> Hi:
> I am a new R user. I have the following question and would appreciate your input
>
> Data1 (data frame 1)
> p1,d1,d2 (p1 is text and d1 and d2 are numeric)
> xyz,10,25
>
> Data2 (data frame 2)
> p1,d1,d2
> xyz,11,15
>
> Now I want to create a new data frame that looks like so below. The fields d1 and s2 are summed by the product key.
> Data3
> p1,d1,d2
> xyz,21 (sum of 10 from Data1 and 11 from Data2),40 (sum of 25 from Data1 and 15 from Data2)
>
> Any other examples of merge you may have will be appreciated. Thanks.
> Satish
Given the nature of your data, having the same column structure with
repeated keys, I would not use merge(), but rbind() the two data frames
together and then use aggregate():
DF <- rbind(Data1, Data2)
> DF
p1 d1 d2
1 xyz 10 25
2 xyz 11 15
> aggregate(DF[-1], list(p1 = DF$p1), sum)
p1 d1 d2
1 xyz 21 40
See ?rbind and ?aggregate
If you search the list archives:
RSiteSearch("merge")
you will yield hundreds of posts showing the use of that particular
function.
HTH,
Marc Schwartz