我有一个Excel表格,其中包含美国每个县的每个行业的就业人数。
它看起来是这样的:
County Industry Employees
a 1 49
a 2 1
b 1 4
b 2 19
...我想计算一下每个县的就业指数( Herfindahl-Hirschman index )。我使用R。给定一些数字,计算HHI很简单:
hhi <- function(x) {
# calculate sum
total <- sum(x)
# calculate share
share <- x*100/total
# add
return(sum(share^2))
}因此,例如,县1的HHI为9608 (= 98^2 + 2^2),县2的HHI为7127。
但是,如何使用该县的HHI创建新的专栏呢?
发布于 2016-09-15 23:27:01
您可以使用dplyr
library(dplyr)
df %>% group_by(County) %>% mutate(HHI = sum((Employees/sum(Employees) * 100)^2))
# Source: local data frame [4 x 4]
# Groups: County [2]
# County Industry Employees HHI
# <fctr> <int> <int> <dbl>
# 1 a 1 50 9615.532
# 2 a 2 1 9615.532
# 3 b 1 4 7126.654
# 4 b 2 19 7126.654或者等效地使用data.table
setDT(df)[, HHI := sum((Employees/sum(Employees) * 100)^2), County][]使用您自己的自定义函数hhi,因为它调用的所有函数都是矢量化的,所以您可以直接在mutate中使用它
df %>% group_by(County) %>% mutate(HHI = hhi(Employees))或者:
setDT(df)[, HHI := hhi(Employees), County][]发布于 2016-09-15 23:30:29
我们可以从base R使用ave (不使用包)
df1$HHI <- with(df1, ave(Employees, County, FUN = hhi))https://stackoverflow.com/questions/39514827
复制相似问题