在R中按组汇总并计算完成百分比。

huangapple go评论57阅读模式
英文:

Summarise and calculate percentage complete by group in R

问题

这是您要的翻译结果:

我有一个看起来像这样的数据框:

example <- data.frame(
  sub = c(rep(1091, 3),
          rep(2091,4)),
  completed_sessions = c(1,0,1,0,1,1,1)
)

我想要按'sub'计算`percent_complete`,通过计算`num_complete/total_entries`来实现。`num_complete`是每个`sub`的'1'的计数,`total_entries`是'PID'的总观察次数。我该如何做到这一点?

这是期望的输出:

example_solution <- data.frame(
  sub = c(1091, 2091),
  num_complete = c(2,3),
  total_entries = c(3,4),
  percent_complete = c(66.67, 75.00)
)

谢谢!

希望这个翻译对您有所帮助。

英文:

I have a dataframe that looks like this:

example &lt;- data.frame(
  sub = c(rep(1091, 3),
          rep(2091,4)),
  completed_sessions = c(1,0,1,0,1,1,1)
)

I want to get the percent_complete by sub, with it calculated by num_complete/total_entries. num_complete is the count of '1's per sub, total_entries is the total number of observations of PID. How can I do this?

This is the desired output:

example_solution &lt;- data.frame(
  sub = c(1091, 2091),
  num_complete = c(2,3),
  total_entries = c(3,4),
  percent_complete = c(66.67, 75.00)
)

Thank you!

答案1

得分: 0

示例 %>%
汇总(num_complete = sum(completed_sessions),
total_entries = n(),
percent_complete = num_complete/total_entries*100,
.by = sub)

子集 num_complete total_entries percent_complete
1 1091 2 3 66.66667
2 2091 3 4 75.00000

英文:
example %&gt;%
   summarise(num_complete = sum(completed_sessions), 
             total_entries = n(),
             percent_complete = num_complete/total_entries*100,
             .by = sub)

   sub num_complete total_entries percent_complete
1 1091            2             3         66.66667
2 2091            3             4         75.00000

huangapple
  • 本文由 发表于 2023年7月28日 02:04:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定