当处于复杂场景中时,dplyr案例

当处于复杂场景中时,dplyr案例,r,dplyr,case-when,R,Dplyr,Case When,假设我在每轮研究中按国家、轮数和类型生成一个概率表。 我需要计算一个重量,这个重量是基于一个人到那时为止参与的回合数。 权重计算为所有概率之和(p)减去所有概率的乘积的倒数,直至一个人参与的那一轮 我曾考虑过使用case_when(),如果我找不到在未来几轮中实现自动化的方法,至少写10轮,但我不确定我的方法是否正确。感谢来自真实R用户的任何指导 For id=1 in the example below, p is 0.78584735 for round=1 and type=2 and c

假设我在每轮研究中按国家、轮数和类型生成一个概率表。 我需要计算一个重量,这个重量是基于一个人到那时为止参与的回合数。 权重计算为所有概率之和(p)减去所有概率的乘积的倒数,直至一个人参与的那一轮

我曾考虑过使用case_when(),如果我找不到在未来几轮中实现自动化的方法,至少写10轮,但我不确定我的方法是否正确。感谢来自真实R用户的任何指导

For id=1 in the example below,
p is 0.78584735 for round=1 and type=2 and country="DE"
p is 0.07271288 for round=2 and type=2 and country="DE"
Then, p_tot should be (0.78584735+0.07271288)- (0.78584735*0.07271288)

#概率表
种子集(1245)
概率表%filter(国家=“DE”和舍入%
总和(p列的所有元素)-乘法(p列的所有元素),
...
...
真的~NA
)
)
#计算重量

df$weight您可以使用每行的值来创建过滤器,而不是对其进行硬编码

通常这样的问题可以通过连接两个表来解决,但是
小于等于
舍入%
变异(
p_tot=概率表%>%
过滤器(p_国家==国家,p_四舍五入%
总结(s=总和(p_p),
m=产品(p_p),
f=s-m)%>%
拉力(f),
重量=1/p_总重量
)
#>来源:本地数据帧[15 x 6]
#>小组:
#> 
#>#A tibble:15 x 6
#>id国家/地区圆形p_总重量
#>            
#>1 DE 2 0.801 1.25
#>2 DE 3 0.447 2.24
#>3 3 DE 11 0 Inf
#>4 4 DE 11 0 Inf
#>5 5 DE 11 0 Inf
#>6德2 0.801 1.25
#>7 7 DE 13 0 Inf
#>8 8 DE 11 0 Inf
#>9英国22 0.5321.88
#>英国310.4752.10
#>11 11英国11 10 Inf
#>12英国330.7621.31
#>13 13英国2 1 0.475 2.10
#>14 14英国2110.4752.10
#>15 15英国22 0.5321.88

由(v0.3.0)创建于2020-06-17非常感谢!我不知道rowwise()。

# Table with probabilities

  set.seed(1245)
  prob_table <- data.frame(country=c(rep("DE",6), rep("UK",6)), 
                           round=c(rep(1,3),rep(2,3),rep(1,3),rep(2,3)),
                           type=c(rep(1:3,2)), p=c(runif(12)))

# Data frame with participants

df <- data.frame(id=c(1:15), country=c(rep("DE",8), rep("UK",7)), 
                 round=c(2,3,1,1,1,2,1,1,2,3,1,3,2,2,2),
                 type=c(2,3,1,1,1,2,3,1,2,1,1,3,1,1,2))

# Calculate total probability

df %<>% mutate(
  p_tot = case_when(
    country=="DE" & round==1 & type==1 
    ~ prob_table%>% filter(country=="DE" & round<=1 & type==1) %>% 
      sum(all elements of p column)-multiply(all elements of p column),

    country=="DE" & round==1 & type==1 
    ~ prob_table%>% filter(country=="DE" & round<=1 & type==1) %>% 
      sum(all elements of p column)-multiply(all elements of p column),

    ...
    ...

    TRUE ~ NA
  )
)


# calculate weight

df$weight <- 1/df$p_tot