【问题标题】:Calculation Proportion in R with Loop?R中的计算比例与循环?
【发布时间】:2022-09-29 19:55:03
【问题描述】:

我有一个类似的数据集:

> dput(df)
structure(list(Surgeon = c(\"John Smith\", \"John Smith\", \"John Smith\", 
\"John Smith\", \"John Smith\", \"John Smith\", \"John Smith\", \"Martin Harris\", 
\"Martin Harris\", \"Martin Harris\", \"Kyle Short\"), Blood.Order = c(\"ABC\", 
\"ABC\", \"DEF\", \"ABC\", \"IJK\", \"ABC\", \"DEF\", \"IJK\", \"ABC\", \"ABC\", 
\"DEF\"), Status = c(\"Returned\", \"Wasted\", \"Returned\", \"Returned\", 
\"Wasted\", \"Wasted\", \"Wasted\", \"Returned\", \"Wasted\", \"Returned\", 
\"Wasted\")), class = \"data.frame\", row.names = c(NA, -11L))

我想根据他们执行了多少事件来计算每个人浪费了多少东西(Stuff.Order)。

例如,我们看到John Smith 执行了 7 个事件。在这7次手术中,他浪费了4次。所以这个计算应该是 4/7=0.5714286。

我想为每个人创建一个循环来执行此操作(找出每个人在他们执行的事件总数中浪费了多少项目)。

谢谢!

  • prop.table(table(df[-2]),1)

标签: r


【解决方案1】:

我们可以在没有循环的情况下执行此操作,即按“外科医生”分组,得到逻辑向量的mean (Status == "Wasted")

library(dplyr)
out <- df %>% 
   group_by(Surgeon) %>% 
   summarise(Prop = mean(Status == "Wasted"))

-输出

out
# A tibble: 3 × 2
  Surgeon        Prop
  <chr>         <dbl>
1 John Smith    0.571
2 Kyle Short    1    
3 Martin Harris 0.333

如果我们需要条形图

library(ggplot2)
ggplot(out, aes(x = Surgeon, y = Prop)) + geom_col()

或使用base R

barplot(proportions(table(df[-2]), 1)[,2])

【讨论】:

  • 谢谢!是否也可以在同一函数中找到“返回”的平均值
  • @Tiffany 你可以把代码改成df %&gt;% group_by(Surgeon) %&gt;%summarise(PropWast = mean(Status == "Wasted"), PropRet = mean(Status == "Returned"))
  • @Tiffany 或以 R 为基础,而不是子集化 barplot(proportions(table(df[-2]), 1))
猜你喜欢
  • 2019-11-30
  • 1970-01-01
  • 2020-07-07
  • 2017-08-13
  • 1970-01-01
  • 2012-11-05
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
相关资源
最近更新 更多