【发布时间】:2019-01-15 17:32:42
【问题描述】:
我使用 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))
我现在想计算每个条目对其组产生的 idex 的贡献量,这意味着我想计算一个新索引,就好像一个值的条目成本为 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 我不知道该怎么做。 欢迎提出任何建议!
【问题讨论】:
-
你能显示预期的输出吗?此外, set.seed 将使其可重现
-
计算不清楚
as if the entry cost is 0