Home > Enterprise >  calculating proportion of each value in a column by applying weight
calculating proportion of each value in a column by applying weight

Time:01-30

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.

CodePudding user response:

Is this what you are looking for?

library(tidyverse)
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
  •  Tags:  
  • Related