-1

I have this brfss2013 data, the third column presents the number of individuals for the second column, and I would like to generate a percentage of the third column by state.

This is what I have.

    X_state checkup1            count
                  
1 Alabama Within past year     5060
2 Alabama Within past 2 years   587
3 Alabama Within past 5 years   330
4 Alabama 5 or more years ago   358
5 Alabama Never                  53

This is what I want to generate using a R code(I did by hand):

X_state checkup1            percentage
             
1 Alabama Within past year     0,7921
2 Alabama Within past 2 years  0,0918
3 Alabama Within past 5 years  0,0516
4 Alabama 5 or more years ago  0,0560
5 Alabama Never                0,0082

How can I generate this percentage by state (having in mind that the DF has data for the whole country)?

Peter
  • 11,500
  • 5
  • 21
  • 31

1 Answers1

1

Here's a way with dplyr package -

DF %>%
  group_by(X_state) %>%
  mutate(percentage = count / sum(count)) %>%
  ungroup()

In base R -

DF$percentage <- with(DF, count / ave(count, X_state, FUN = sum))
Shree
  • 10,835
  • 1
  • 14
  • 36