Skip to content

Dividing rows in groups

1 message · jim holtman

#
This will handle all the columns; it assumes the ones you want to start
with are in column 2 through the end:
+ 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", header = TRUE)
+         group_by(ID) %>%
+         do({  # now process and indeterinant number of columns
+             result <- .  # get original input
+             for (i in 2:ncol(result)){
+                 result[[i]] <- result[[i]] / sum(result[[i]], na.rm =
TRUE)
+             }
+             result  # return value
+         })
Source: local data frame [10 x 3]
Groups: ID [5]

      ID         A     B
   (int)     (dbl) (dbl)
1      1 1.0000000   0.4
2      1 0.0000000   0.6
3      2 0.8333333    NA
4      2 0.1666667   1.0
5      3 1.0000000   1.0
6      4        NA    NA
7      4 0.0000000   1.0
8      4 1.0000000   0.0
9      5 0.2222222   1.0
10     5 0.7777778    NA



Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.

On Sun, Apr 24, 2016 at 12:02 PM, Saba Sehrish <sabasehrish at yahoo.com>
wrote: