0

I have a data set that look like the following: https://i.stack.imgur.com/0i8Cj.png

Name | State | Zipcode | County_name | average payment | Frequency

My desired output would be to group by State and have the Median payment using the average payment and Frequency columns.

I know how to do this for the overall dataset

median(rep(Clean$medicare_average_payment, Clean$Frequency))        

but not sure how to do this by State Thank you

Matt S
  • 55
  • 1
  • 6
  • Possible duplicate of [How to sum a variable by group?](http://stackoverflow.com/questions/1660124/how-to-sum-a-variable-by-group) – MichaelChirico May 03 '16 at 03:26

2 Answers2

1

We can try with dplyr

library(dplyr)    
Clean1 <- Clean[rep(1:nrow(Clean), Clean$Frequency),]
Clean1 %>%
      group_by(State) %>%
      summarise(Median = median(medicare_average_payment))

Or using data.table

library(data.table)
setDT(Clean)[, .(Median = median(rep(medicare_average_payment, Frequency))) , State]
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You can use by to do split the data frame and perform this function on each piece:

by(Clean, Clean$State, 
   FUN=function(x) median(rep(x$medicare_average_payment, x$Frequency))
)
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112