簡體   English   中英

如何計算 R 中的多個組的條件熵 ..我在哪里 go 錯了

[英]How to calculate conditional entropy by multiple groups in R ..where did I go wrong

我已經閱讀了許多與我相關的問題,但是我無法弄清楚我的代碼有什么問題

我使用的 package 是“dplyr”和“infotheo”

這里使用 infotheo 是condentropy(time2, time1)

我的數據就像

id <- c("1", "1", "1", "1", "2", "2", "2", "2", "3", "3", "3", "3")
cond <- c("1", "2", "1", "2", "1", "2", "1", "2", "1", "2", "1", "2")
time1 <- c("1", "3", "3", "2", "3", "3", "1", "1", "1", "2", "2", "1")
time2 <- c("3", "3", "2", "3", "3", "1", "1", "1", "2", "2", "1" ,"1")
df <- data.frame(id, cond, time1, time2)

我想通過 id 和條件來計算它,這意味着我將從 3 個人的兩個條件下獲得 6 個熵值。 這是我的代碼

df %>%
group_by(df$id, df$cond) %>%
summarize(condentropy(df$time2, df$time1))

為什么我對所有組只有一個值?

在此處輸入圖像描述

我在這里先向您的幫助表示感謝!

像這樣的東西

首先,將您的數據轉換為數字

df <- df %>% type_convert()

-- Column specification ------------------------------------------
cols(
  id = col_double(),
  cond = col_double(),
  time1 = col_double(),
  time2 = col_double()
)

其次,要設法尋找相關手段,

df  %>%
    group_by(id, cond) %>%
    summarise(mean = mean(id))
`summarise()` has grouped output by 'id'. You can override using the `.groups` argument.
# A tibble: 6 x 3
# Groups:   id [3]
     id  cond  mean
  <dbl> <dbl> <dbl>
1     1     1     1
2     1     2     1
3     2     1     2
4     2     2     2
5     3     1     3
6     3     2     3

第三,研究此頁面以獲取其他示例。

將時間列轉換為數字,執行分組和匯總。 不要將 df$ 與 dplyr 動詞一起使用,並確保將 condentropy(...) 的值分配給列名。 問題的主題是指均值,但代碼建議您要計算條件熵,因此我們提供兩者。

library(dplyr)
library(infotheo)

df %>%
  mutate(time1 = as.numeric(time1), time2 = as.numeric(time2)) %>%
  group_by(id, cond) %>%
  summarize(cond_ent = condentropy(time2, time1), 
            mean1 = mean(time1), mean2 = mean(time2), .groups = "drop")

使用type.convert(as.is = TRUE)來獲取數值變量,然后用across summarise :你不必使用$

這個:

library(dplyr)
library(infotheo)
df %>% 
  as_tibble() %>% 
  type.convert(as.is=TRUE) %>% 
  group_by(id, cond) %>% 
  summarise(mean = mean(c(time1, time2)))

Output:

     id  cond  mean
  <int> <int> <dbl>
1     1     1  2.25
2     1     2  2.75
3     2     1  2   
4     2     2  1.5 
5     3     1  1.5 
6     3     2  1.5 

或者

library(dplyr)
df %>% 
  as_tibble() %>% 
  type.convert(as.is=TRUE) %>% 
  group_by(id, cond) %>% 
  summarise(across(starts_with("time"), mean))

Output:

     id  cond time1 time2
  <int> <int> <dbl> <dbl>
1     1     1   2     2.5
2     1     2   2.5   3  
3     2     1   2     2  
4     2     2   2     1  
5     3     1   1.5   1.5
6     3     2   1.5   1.5

暫無
暫無

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

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