Search code examples
rmedian

Calculate median based on counts of value


I have a following data frame:

   numbers Freq
1        4    2
2        5    1
3       23    2
4       34    2

I know how to calculate median in r when frequency is 1 (median(`numbers`, na.rm = TRUE)), but how to do that when frequency is different from 1?


Solution

  • We can create a logical index with !=, use that to subset the 'numbers' column and get the median

    with(df1, median(numbers[Freq != 1], na.rm = TRUE))
    #[1] 23
    

    data

    df1 <- structure(list(numbers = c(4L, 5L, 23L, 34L), Freq = c(2L, 1L, 
    2L, 2L)), class = "data.frame", row.names = c("1", "2", "3", 
    "4"))