How to calculate median of profits for a particular country

前端 未结 3 1668
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 15:32

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.

3条回答
  •  轮回少年
    2021-01-28 15:45

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

提交回复
热议问题