I have a dataframe with company quarterly data, and I have two questions:
1: How can I keep records for only those companies with four quarters of data (as companies sometimes appear with 1, 2 or 3 quarters of data but I need 4 quarters for each company across the entire dataframe)
2: Because I have quarterly data, I would like to take the annual average or sum (based on variable type) across all four quarters given 2 conditions: year and company.
For instance, Company i in 1984 would have an average inventory value and total revenue, say I1984 and REV1984 respectively, based on four distinct quarterly values. I am currently using these lines of code - for the mean and sum - but R keeps returning "NA" and I've searched and searched for alternatives but nothing seems to work:
Company i_ I1984 <- with(R, mean(I [FY == "1984" & Co == "AAR CORP" ]))
Company i_ REV1984 <- with(R, sum(REVQ [FY == "1984" & Co == "AAR CORP" ]))
R is my dataframe I <- quarterly inventory REVQ <- quarterly revenue
Clearly, the values in quotes will be made dynamic as I find each new average/sum value and place in a new data.frame
.
Any help would be highly appreciated. Thank you
I've included an example code below:
company<-c("xray", "xray", "xray", "xray", "foxrot", "foxrot", "delta", "kilo", "kilo" )
qtr <-c("1","2","3","4", "1", "2","4", "2","3")
IQ <- rnorm(9,0,10)
REVQ <- rnorm(9,0,10)
AssetQ <- rnorm(9,0,10)
CashQ <- rnorm(9,0,10)
#Modified dataframe
data<-data.frame( company, qtr, IQ, REVQ, AssetQ, CashQ )
In this example 'xray' should be the only company for which we take a mean/sum.