簡體   English   中英

如何獲取數據幀中的頻率?

[英]How to get the frequency in a data frame?

我有這個數據框,我希望按集群將頻率作為每個事件的一部分。 例如,由於 E2 在 C2 中出現 2 次,並且 C2 有 4 個事件,因此分數將為 0.5。

data <- data.frame(Event=c("E1", "E2", "E2","E3", "E4"), Cluster=c("C1", "C2", "C2", "C2", "C2"))

Event     Cluster   
E1          C1
E2          C2
E2          C2
E3          C2
E4          C2

這是我想要的輸出:

Event     Cluster   Freq
E1          C1       1
E2          C2       0.5
E3          C2       0.25
E4          C2       0.25

使用dplyr ,我們可以count ClusterEvent每個級別,然后計算每個Cluster的比率。

library(dplyr)

data %>%
 count(Cluster, Event, name = "Freq") %>%
 group_by(Cluster) %>%
 mutate(Freq = Freq/sum(Freq))

#  Cluster Event  Freq
#  <fct>   <fct> <dbl>
#1 C1      E1     1   
#2 C2      E2     0.5 
#3 C2      E3     0.25
#4 C2      E4     0.25

在基礎 R 中,我們可以使用tableprop.table ,它們將具有相同的信息但輸出格式不同。

prop.table(table(data), 2)

#     Cluster
#Event   C1   C2
#   E1 1.00 0.00
#   E2 0.00 0.50
#   E3 0.00 0.25
#   E4 0.00 0.25

這是另一種使用基礎 R 的解決方案:

data2 = unsplit(lapply(split(data, data$Cluster), function(df) {
    df$Freq = nrow(df)
    df
}), data$Cluster)

aggregate(data2[,"Freq", drop=FALSE], data2[c("Event","Cluster")],
          function(x) length(x)/x[1])

##   Event Cluster Freq
## 1    E1      C1 1.00
## 2    E2      C2 0.50
## 3    E3      C2 0.25
## 4    E4      C2 0.25

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM