dataframe - Groupwise computation in R -


this question has answer here:

i have grouped , summarized data frame in r have table like:

group | value | count ==========================     |   1   |   4     |   2   |   2     |   10  |   4    b  |   3   |   2    b  |   4   |   4    b  |   2   |   3    c  |   5   |   3    c  |   2   |   6 

i interested in finding out relative frequency of value 2 within each group:

group | relative freq of 2 ==========================     |  2/(4+2+4) = 0.2    b  |  3/(2+4+3) = 0.33    c  |  6/(3+6) = 0.67 

is there simple, elegant way of calculating in r, other writing bunch of code loops , conditionals? possibly using dplyr.

using dplyr, after grouping 'group', subset 'count' 'value' 2 (assuming there single 'value' of 2 per each 'group') , divide sum of 'count'

library(dplyr) df1 %>%    group_by(group) %>%     summarise(relfreq = round(count[value==2]/sum(count), 2)) #  group relfreq #  <chr>   <dbl> #1        0.20 #2     b    0.33 #3     c    0.67 

the corresponding data.table option is

library(data.table) setdt(df1)[, .(relfreq = round(count[value == 2]/sum(count),2)), = group] 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -