Search code examples
rmedian

How to calculate median of profits for a particular country


Hello folks, I am new to R and I am trying to compute median profit for a particular country in a data frame.I tried below one but it doesn't work for me.

data("Forbes2000", package = "HSAUR")
median(Forbes2000[,"sales","country"="United States"])

Solution

  • median(Forbes2000$sales[Forbes2000$country == "United States"])
    

    Though it's hard to be certain without knowing what your data frame looks like. If you want to get a data.frame with the median of every country instead of just one, you could do:

    library(plyr)
    ddply(Forbes2000, "country", function(d) median(d$sales))
    

    (You would have to install the plyr package first, for example by doing install.packages("plyr")).