我已经对R中的一个数据帧进行了分组和汇总,因此我现在有一个表,如下所示:
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在每组中的相对频率:
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。
发布于 2016-09-13 13:19:15
使用dplyr,在按“组”分组后,我们将“计数”子集,其中“值”是2(假设每个“组”只有一个值为2),并除以“计数”的sum。
library(dplyr)
df1 %>%
group_by(Group) %>%
summarise(RelFreq = round(Count[Value==2]/sum(Count), 2))
# Group RelFreq
# <chr> <dbl>
#1 A 0.20
#2 B 0.33
#3 C 0.67相应的data.table选项为
library(data.table)
setDT(df1)[, .(RelFreq = round(Count[Value == 2]/sum(Count),2)), by = Group]发布于 2016-09-13 14:03:00
这是一个基本的R解决方案:
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 发布于 2016-09-13 13:41:00
您可以使用与for循环相同的逻辑
for(i in unique(df$Group)){
df$Relative_freq_of_2[df$Group==i] <- round(df$Count[df$Value==2 & df$Group==i]/sum(df$Count[df$Group==i]),2)
}
df <- unique(df[,c("Group","Relative_freq_of_2")])
Group Relative_freq_of_2
A 0.20
B 0.33
C 0.67https://stackoverflow.com/questions/39462610
复制相似问题