【问题标题】:Loop through dataset to calculate diveristy循环遍历数据集以计算多样性
【发布时间】:2018-11-29 19:48:49
【问题描述】:

我有一个这样的数据集:

 set.seed(1345)
 df<-data.frame(month= c(rep(1,10), rep(2, 10), rep(3, 10)), 
           species=sample(LETTERS[1:10], 30, replace= TRUE))

我想遍历每个月并计算物种多样性。我知道library("vegan") 中的diversity 之类的功能,并且知道使用该路线(下面提供的代码)解决我的问题,但作为我自己的循环练习,我正在尝试创建一个for loop 或显示的函数香农分集和辛普森分集的具体计算,让每个指数的计算都不神秘。它们使用以下公式计算:

到目前为止,我已经为辛普森一家尝试了以下方法:

df <- 
 df %>% 
  group_by(month, species) %>% 
  summarise(freq = n()) 

div<-NA
 for (i in length(unique(df$month))) {
 sum<- sum(df$freq)
 for (i in unique (df$freq)){
 p<- df$freq /sum
 p.sqrd<-p*p
 div[i]<-1/sum(p.sqrd)
   }}

Shannons 如下:

df <- 
 df %>% 
  group_by(month, species) %>% 
  summarise(freq = n()) 

div<-NA
 for (i in length(unique(df$month))) {
 sum<- sum(df$freq)
 for (i in unique (df$freq)){
 p<- df$freq /sum
 log.p<-ln(p)
 div[i]<- sum(p[i]*ln(p[i]))
   }}

我没有创建一个成功的循环,我希望帮助正确地索引这个循环并创建一个最有效的循环(即将df &lt;- df %&gt;% group_by(month, species) %&gt;% summarise(freq = n()) 合并到循环中)和一个清楚地说明循环内等式的 for 循环。

使用diversity 函数,以下是辛普森多样性的答案:

library("tidyverse")
df <- 
 df %>% 
 group_by(month, species) %>% 
 summarise(freq = n()) 

# Cast dataframe of interaction frequencies into a matrix
library("reshape2")
ph_mat<- dcast(df,  month~ species)
ph_mat[is.na(ph_mat)] <- 0 #changes 

library("vegan")
df<- data.frame(div=diversity(ph_mat, index="simpson"), 
               month=unique(ph_mat$month))

对于香农来说:

library("vegan")
df<- data.frame(div=diversity(ph_mat, index="shannon"), 
               month=unique(ph_mat$month))

【问题讨论】:

    标签: r function for-loop


    【解决方案1】:

    我在这里有一个不包含 for 循环的解决方案,但我定义并解释了一个计算每个索引的函数(这并不神秘!)它计算每个月的每个多样性指标。它使用来自dplyrgroup_by()summarize() 函数。

    set.seed(1345)
    df<-data.frame(month= c(rep(1,10), rep(2, 10), rep(3, 10)), 
                   species=sample(LETTERS[1:10], 30, replace= TRUE))
    
    calc_shannon <- function(community) {
      p <- table(community)/length(community) # Find proportions
      p <- p[p > 0] # Get rid of zero proportions (log zero is undefined)
      -sum(p * log(p)) # Calculate index
    }
    
    calc_simpson <- function(community) {
      p <- table(community)/length(community) # Find proportions
      1 / sum(p^2) # Calculate index
    }
    
    diversity_metrics <- 
      df %>% 
      group_by(month) %>% 
      summarize(shannon = calc_shannon(species),
                simpson = calc_simpson(species))
    

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-22
      • 1970-01-01
      相关资源
      最近更新 更多