entropy(熵):

library(dplyr)

df %>% 
  group_by(Year, Region) %>% 
  summarise(shannon_entropy = sum(-prob*log2(prob)))

# Output:
# # A tibble: 6 x 3
# # Groups:   Year [2]
#    Year Region shannon_entropy
#   <int> <chr>           <dbl>
# 1  2000 east             1.37
# 2  2000 west             1.37
# 3  2001 east             1.37
# 4  2001 west             1.37
# 5  2002 east             1.37
# 6  2002 west             1.37

其中,-prob*log2(prob)表示每个类别的信息量,sum()表示对所有类别的信息量求和,得到熵的值

dplyr按照Year Region分组计算prob列的shannon

原文地址: https://www.cveoy.top/t/topic/fe7n 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录