我使用 dplyr 计算索引。该指数是组中每个条目与总条目之间的平方比的总和。
library(dplyr)
set.seed(1e2)
firm_id <- sample(1:3, 1e2, rep=T)
pro_id <- sample(1:8, 1e2, rep=T)
emplo_id <- sample(1:5, 1e2, rep=T)
cost <- round(abs(rnorm(1e2, 20)), 2)
df <- data.frame(firm_id, pro_id, emplo_id, cost)
df_index <- df %>% group_by(firm_id,pro_id) %>%
mutate(INDEX = sum((cost/sum(cost))^2))
我现在想计算每个条目对其组生成的索引有多少贡献,这意味着我想计算一个新索引,就像一个值的条目成本为 0 一样,并且对于每个条目来说就像在一个循环中一样(然后将新索引除以旧索引)。
预期结果:
firm_id <- c(1,1,1)
pro_id <- c(1,1,1)
emplo_id <- c(1:3)
cost <- c(1,50,100)
INDEX <- rep(0.5482654,3)
newINDEX <- c(0.5555556,0.9803941,0.9615532)
df_index <- data.frame(firm_id, pro_id, emplo_id, cost, INDEX, newINDEX)
对于 mutate,我不知道该怎么做。 欢迎任何建议!
最佳答案
您可以使用purrr::map_dbl()
循环遍历每个中的行索引
组,然后应用一个函数来替换给定索引处的 cost
0,然后重新计算索引。这是一个包含数据的示例
您给出了预期输出:
library(dplyr)
library(purrr)
# The function used to calculate the index value
index <- function(x) sum((x / sum(x)) ^ 2)
df_index %>%
group_by(firm_id, pro_id) %>%
mutate(new = map_dbl(row_number(), function(i) {
index(replace(cost, i, 0))
}))
#> # A tibble: 3 x 7
#> # Groups: firm_id, pro_id [1]
#> firm_id pro_id emplo_id cost INDEX newINDEX new
#> <dbl> <dbl> <int> <dbl> <dbl> <dbl> <dbl>
#> 1 1 1 1 1 0.548 0.556 0.556
#> 2 1 1 2 50 0.548 0.980 0.980
#> 3 1 1 3 100 0.548 0.962 0.962
通过附加的辅助函数,您还可以以更简洁的方式执行此操作:
index_without <- function(i, x) {
map_dbl(i, function(i) index(replace(x, i, 0)))
}
df_index %>%
group_by(firm_id, pro_id) %>%
mutate(new = index_without(row_number(), cost))
#> # A tibble: 3 x 7
#> # Groups: firm_id, pro_id [1]
#> firm_id pro_id emplo_id cost INDEX newINDEX new
#> <dbl> <dbl> <int> <dbl> <dbl> <dbl> <dbl>
#> 1 1 1 1 1 0.548 0.556 0.556
#> 2 1 1 2 50 0.548 0.980 0.980
#> 3 1 1 3 100 0.548 0.962 0.962
由 reprex package 创建于 2018-08-08 (v0.2.0.9000)。
关于r - 在 mutate 内循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51746893/