[R] Dividing rows in groups

David Winsemius dwinsemius at comcast.net
Sun Apr 24 07:42:15 CEST 2016


> On Apr 23, 2016, at 9:46 PM, Saba Sehrish via R-help <r-help at r-project.org> wrote:
> 
> Hi 
> 
> 
> I have two data frames as shown below (second one is obtained by aggregating rows of similar IDs in df1.). They both have similar number of columns but rows of df2 are lesser than rows of df1. 
> 
> 
> df1: 
> ID       A             B 
> 1         1             2 
> 1         0             3 
> 2        5             NA 
> 2         1             3 
> 3         1             4 
> 4         NA           NA 
> 4         0             1 
> 4         3             0 
> 5         2             5 
> 5         7           NA
> 
> 
> df2: 
> ID       A          B 
> 1         1          5 
> 2         6          3 
> 3         1          4 
> 4         3          1 
> 5        9          5 
> 
> Now, to obtain weight of each value of df1, I want to divide each row of df1 by the row of df2 having similar ID. What I want is as below: 
> 
> ID    A    B 
> 1    1    0.4 
> 1    0    0.6 
> 2    0.83  NA 
> 2    0.17  1 
> 3    1     4 
> 4    NA    NA 
> 4    0     1 
> 4    1     0 
> 5    0.22  1 
> 5    0.78  NA 
> 
> 
> Kindly guide me in this regard. 

Do a merge on "ID"  and then calculate.


-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list