I have a dataframe with company quarterly data and have this question:
How can I retain records for only those companies with 4 quarters of data (as companies sometimes
We can use data.table
library(data.table)
setDT(data)[data[, .I[uniqueN(qtr)==4], by = company]$V1]
Or
setDT(data)[, if(uniqueN(qtr)==4) .SD, by = company]
# company year qtr IQ REVQ AssetQ CashQ
#1: xray 1984 1 -5.827832 8.221870 9.6688477 -10.6321121
#2: xray 1984 2 3.521643 -1.096940 -4.5014798 -0.9196087
#3: xray 1984 3 -7.526160 -4.155428 -10.6556271 7.6872401
#4: xray 1984 4 -7.255974 3.717738 -1.7913910 9.6325437
#5: kilo 1989 1 2.252885 -19.238773 9.7476758 4.0115274
#6: kilo 1989 2 9.018055 -12.411381 -0.3772812 6.8339812
#7: kilo 1989 3 -12.221085 -13.040805 7.3529403 9.1510647
#8: kilo 1989 4 2.088668 -7.753041 1.5701738 -11.2252986