I have data that looks like this:
dat <- data.frame(county_id = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"),
income_level = c("income1", "income2", "income3", "income4",
"income5","income1", "income2", "income3", "income4", "income5"),
frequency = c(4, 1, 5, 11, 4, 7, 12, 0, 5, 7),
total = c(25, 25, 25, 25, 25, 31, 31, 31, 31, 31)
)
I would like to identify the median income level for each unique county (in the code above, there are two counties, but the actual dataset I am working with has thousands).
For instance, in County A the median number is the 13th observation when arranged in ascending order. This means the median for County A falls within income level 4.
For County B, the median is the 16th observation, which means the median income level for County B is income level 2.
I would like to use some version of a for loop, lapply, etc. to create a new column that would return the median income level for each unique county in the dataset (e.g., the median income bracket for County A, the median income bracket for County B, etc.)
Any guidance or suggestions would be much appreciated.