R中的分组计算 [英] Groupwise computation in R
本文介绍了R中的分组计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经对R中的数据帧进行了分组和汇总,因此现在有了一个像这样的表:
I have grouped and summarized a data frame in R so that I now have a table like:
Group | Value | Count
==========================
A | 1 | 4
A | 2 | 2
A | 10 | 4
B | 3 | 2
B | 4 | 4
B | 2 | 3
C | 5 | 3
C | 2 | 6
我有兴趣找出每个组中值2的相对频率:
I am interested in finding out the relative frequency of the value 2 within each group:
Group | Relative freq of 2
==========================
A | 2/(4+2+4) = 0.2
B | 3/(2+4+3) = 0.33
C | 6/(3+6) = 0.67
在R中是否有一种简单,优雅的计算方法,而不是编写带有循环和条件的代码?可能使用dplyr。
Is there a simple, elegant way of calculating this in R, other than writing a bunch of code with loops and conditionals? Possibly using dplyr.
推荐答案
这是基本的R解决方案:
Here is a base R solution:
sapply(split(df1, df1$Group),
function(x) round(sum(x$Count[x$Value == 2]) / sum(x$Count), 2))
## A B C
## 0.20 0.33 0.67
这篇关于R中的分组计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文