簡體   English   中英

如何聚合數據集並計算 R 中跨組的連續變量的熵?

[英]How can I aggregate a data set and calculate entropy of a continuous variable across groups in R?

我想計算 R 中每個組的連續變量的熵。

以下是數據示例:

id group X 1 1 1 28 2 2 1 45 3 3 2 21 4 4 2 46 5 5 3 82 6 6 3 98

實際上有 273 個組和 X 以外的更多變量。

我希望能夠為每個“組”計算 X 的熵。

我曾嘗試在 tidyr 中使用 group_by 和 summarize 命令,但我認為沒有合適的熵命令。

希望有一個簡單的解決方案。

提前致謝。

R 中有一個entropy package。

#install.packages('entropy')
library(entropy)

df %>% 
  group_by(group) %>% 
  mutate(entropy = entropy(X))

給我們:

     id group     X entropy
  <dbl> <dbl> <dbl>   <dbl>
1     1     1    28   0.666
2     2     1    45   0.666
3     3     2    21   0.622
4     4     2    46   0.622
5     5     3    82   0.689
6     6     3    98   0.689

或者對於匯總結果:

df %>% 
  group_by(group) %>% 
  summarize(entropy = entropy(X))

給我們:

  group entropy
  <dbl>   <dbl>
1     1   0.666
2     2   0.622
3     3   0.689

數據:

df <- structure(list(id = c(1, 2, 3, 4, 5, 6), group = c(1, 1, 2, 2, 
3, 3), X = c(28, 45, 21, 46, 82, 98)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

在基數 R 中,您可以將熵 function 寫在外面,而不是每次都重新定義它。 IE

  entropy_base <- function(x) -sum((x<-prop.table(x))*log(x))

如果你想總結:

aggregate(X~group,df, entropy_base)
  group         X
1     1 0.6657808
2     2 0.6218199
3     3 0.6891913

如果你想變異:

transform(df,entopy=ave(X,group,FUN = entropy_base))
  id group  X    entopy
1  1     1 28 0.6657808
2  2     1 45 0.6657808
3  3     2 21 0.6218199
4  4     2 46 0.6218199
5  5     3 82 0.6891913
6  6     3 98 0.6891913

我會在 plyr package 中推薦 ddply function: https://www.rdocumentation.org/packages/plyr/versions/1.8.6/topics/ddply

這個 function 允許你傳遞數據,列來分組,並應用一個 function。

例子:

ddply(data, .(Group), summarise, Entropy(x,Y))

在我有 Entropy(x,Y) 的地方,您可以包含您想要的任何熵 function。

暫無
暫無

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

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