How to calculate median of profits for a particular country

杀马特。学长 韩版系。学妹 提交于 2019-12-20 07:34:51

问题


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"])

回答1:


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")).




回答2:


David already answered your initial question and showed you one way to find the median for multiple countries. Here is another way:

You can split the data.frame by country to create a list of data.frames for each country

L <- split(Forbes2000, Forbes2000$country)

Then, you can apply a function to each component of the list with either lapply or sapply. (sapply simplifies the result to an array, whereas lapply returns a list)

sapply(L, function(x) {
    median(x$sales)
})

or, in one line

sapply(split(Forbes2000, Forbes2000$country), function(x) median(x$sales))



回答3:


I was able to calculate median values for a metric in column 11 by US state in dataframe 'outcome3' using:

tapply(outcome3[,11], outcome3$State, median)



来源:https://stackoverflow.com/questions/12185319/how-to-calculate-median-of-profits-for-a-particular-country

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!