I'm coming from Stata and struggling to get used to group_by in dplyr. Perhaps using group_by is the wrong approach, but if you know Stata, you'll understand why I'm trying to use it (I think).
I'd like to transform the data as shown below:
Essentially, I'm trying to collapse each NAICS code into a single row, and to create columns for the 5 statistics under CONC and HHI for each NAICS code (the 4 values for CONC and one for HHI, ignoring the Xs)
The data is here. The code I'm trying is as follows:
ManufMktConc <- read.csv("Manufacturing.csv",
stringsAsFactors = FALSE)
ManufMktConc %<>%
tbl_df %>%
slice(-1) %>%
filter(CONCENFI.display.label!="All companies") %>%
select(-GEO.id,-GEO.id2,-GEO.display.label,-COMPANY,-RCPTOT,-YEAR.id)
ManufMktConc_byInd <- group_by(ManufMktConc,NAICS.id)
ManufMktConc_byInd %<>%
arrange(CONCENFI.id) %>%
mutate(FourFirm = ManufMktConc_byInd$CCORCPPCT[ManufMktConc_byInd$CONCENFI.id=="856"])
That gives me the following error:
> ManufMktConc_byInd %<>% arrange(CONCENFI.id) %>% mutate(FourFirm=ManufMktConc_byInd$CCORCPPCT[ManufMktConc_byInd$CONCENFI.id=="856"])
Error: incompatible size (651), expecting 4 (the group size) or 1
So I can tell that I am asking R to stick the 651 instances of ManufMktConc_byInd$CONCENFI.id == "856"
into the group of 4. I guess this is where my understanding of group_by falls apart. Why isn't my logical statement only applied within each group?
Thank you.