【问题标题】:R dplyr sum based on conditionsR dplyr sum 基于条件
【发布时间】:2017-08-22 05:02:35
【问题描述】:

我正在尝试使用 dplyr 根据其他列中的变量对一列进行乘法和求和。

location = c("LBJ", "LBJ", "LBJ","LBJ") 
sample = c("100", "100", "100","100") 
sum = c(0,1,2,3) 
n = c(200,100,20,24)
df = data.frame(location, sample, sum,n)
df
  location sample sum   n
1      LBJ    100   0 200
2      LBJ    100   1 100
3      LBJ    100   2  20
4      LBJ    100   3  24

我想计算 ( (n where sum == 0) + ((n where sum == 1) / 2 ) ) / (所有 n 的总和)。

我将拥有多个独立运行的位置和样本,因此我想在 dplyr 中使用 group_by 命令。

感谢您的帮助。

【问题讨论】:

  • 那么这个样本数据的期望输出是什么?我无法从您的描述中看出价值应该是什么。你是想总结还是变异?

标签: r dplyr


【解决方案1】:

这是你想要的吗?

library(dplyr)

df%>%group_by(location)%>%dplyr::mutate(Rate=mean(n[which(sum<=1)])/sum(n))

# A tibble: 4 x 5
# Groups:   location [1]
  location sample   sum     n      Rate
    <fctr> <fctr> <dbl> <dbl>     <dbl>
1      LBJ    100     0   200 0.4360465
2      LBJ    100     1   100 0.4360465
3      LBJ    100     2    20 0.4360465
4      LBJ    100     3    24 0.4360465

【讨论】:

  • 或者少一点代码df %&gt;% mutate(Rate = ((n[sum == 0] + n[sum == 1])/2)/sum(n))
  • @biomiha 他有多个位置
  • 自我注意:使用base R which 像这样variable1[which(condition_on(variable2))]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 2019-09-05
  • 2018-06-23
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多