Diversity Index - Vegan Package

41 Views Asked by At

I am trying to calculate the Simpson's Diversity Index, and I am wondering if I can keep the row names using the vegan package.

My dataset currently looks something like this:

           hab   Sp1   Sp2
1     habitat1   1645  1550
2     habitat2   2935  3060
3     habitat3   4780  2875
4     habitat4   3370  3500
5     habitat5   3730  2270
6     habitat6   2475  1140
7     habitat7   1405  1160
8     habitat8   6180  4145
9     habitat9    795   140
10    habitat10  4745  4595

The code I am using is:

data_simp %>% 
  diversity("simp")

Error in diversity(., "simp") : input data must be numeric

I managed to get the Simpson's indices for each row when I deleted the first column in my dataset. However, I would like to keep the first column to create a new dataset with the name of the 'habitat' and the correspondent Simpson's Diversity Index.

Is it possible?

Thank you :)

2

There are 2 best solutions below

0
Alice On BEST ANSWER

After watching this video on Youtube, I found the answer to my question.

I managed to run the index using the wide format of the dataset, instead of the long format.

           hab   value  Sp
1     habitat1   1645  Sp1
2     habitat1   1550  Sp2
3     habitat2   2935  Sp1
4     habitat2   3060  Sp2
4     habitat3   4780  Sp1
5     habitat3   2875  Sp2

The code:

data_simp %>% 
  group_by(hab) %>% 
  summarise(simpson = simpson(value))

The result:

   hab              simpson
   <chr>            <dbl>
 1 habitat1          0.500
 2 habitat2          0.500
 3 habitat3          0.469
3
PBulls On

Is there any reason you cannot keep them separate and merge back in? For example:

df <- data.frame(
  hab = paste0("habitat", 1:10),
  Sp1 = c(1645, 2935, 4780, 3370, 3730, 2475, 1405, 6180, 795, 4745),
  Sp2 = c(1550, 3060, 2875, 3500, 2270, 1140, 1160, 4145, 140, 4595)
)

data_simp <- cbind.data.frame(df$hab, vegan::diversity(df[,2:3]))
#> 1  habitat1  0.6927051
#> 2  habitat2  0.6929298
#> 3  habitat3  0.6618545
#> ...

(you might want to add more informative column names after this step)