【问题标题】:Loop within mutate变异内循环
【发布时间】: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

标签: r loops dplyr


【解决方案1】:

您可以使用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 (v0.2.0.9000) 于 2018 年 8 月 8 日创建。

【讨论】:

    猜你喜欢
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2022-11-02
    • 2017-10-30
    • 1970-01-01
    相关资源
    最近更新 更多