Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

calculating proportion of each value in a column by applying weight

suppose I have following data:

df<- data.frame(province= c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2),marital=c(1,1,1,2,1,1,2,2,2,1,1,1,2,2,1,2),
                education=c(3,2,3,2,3,3,3,2,2,2,3,2,3,2,3,2), weight= c(10.5,11.4,10.1,11.5,10.1,10.2,12.1,13.1,14.1,12.1,13.2,12.2,10.1,12.1,13.2,12.4))

what I want is weighted proportion of 1 to 2 in marital and weighted proportion of each value in education based on province. because I did not know how to weight data I just show my unweighted desire output:

     province  marital education2 education3
1        1     0.625      0.375      0.625
2        2     0.5        0.625      0.375

thank you in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Is this what you are looking for?

df %>%
  group_by(province) %>%
  count(marital, education, wt = weight) %>%
  summarize(marital = sum(n[marital == 1])/sum(n),
            education2 = sum(n[education == 2])/sum(n),
            education3 = sum(n[education == 3])/sum(n))

# A tibble: 2 x 4
  province marital education2 education3
     <dbl>   <dbl>      <dbl>      <dbl>
1        1   0.588      0.404      0.596
2        2   0.510      0.633      0.367
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading