基于函数创建新列

wwl*_*wwl 0 r

我有一个 Excel 表格,其中包含美国每个县每个行业的就业人数。

它看起来像这样:

County   Industry  Employees
a        1         49
a        2         1
b        1         4
b        2         19
...
Run Code Online (Sandbox Code Playgroud)

我想计算每个县就业的Herfindahl-Hirschman 指数(HHI)。我正在使用 R。给定一些数字,计算 HHI 很容易:

hhi <- function(x) {
  # calculate sum
  total <- sum(x)
  
  # calculate share
  share <- x*100/total
  
  # add
  return(sum(share^2))
  
}
Run Code Online (Sandbox Code Playgroud)

因此,例如,县 1 的 HHI 为 9608 (= 98^2 + 2^2),县 2 的 HHI 为 7127。

但是,如何使用该县的 HHI 创建一个新列?

Psi*_*dom 5

您可以使用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
Run Code Online (Sandbox Code Playgroud)

或者等效地,使用data.table

setDT(df)[, HHI := sum((Employees/sum(Employees) * 100)^2), County][]
Run Code Online (Sandbox Code Playgroud)

使用您自己的自定义函数hhi,由于它调用的所有函数都是矢量化的,您可以直接将其用于mutate

df %>% group_by(County) %>% mutate(HHI = hhi(Employees))
Run Code Online (Sandbox Code Playgroud)

或者:

setDT(df)[, HHI := hhi(Employees), County][]
Run Code Online (Sandbox Code Playgroud)