I have a dataframe(df)as follows:
Year PlotNo HabitatType Sp1 Sp2 Sp3 Sp4
2000 1 GH 0 1 2 3
1988 3 KL 2 3 4 5
where, Sp
stands for Species and its columns represent abundance value.
I'm trying to find the Simpson's diversity for each row in the dataframe. I have attempted the following for loop:
require(vegan)
y <- for(i in 1:nrow(df)) {
row <- df[i,4:50] #Assuming 50 columns
diversity(row, "simp")
}
However, I keep running into an error as follows :
Error in sum(x) : invalid 'type' (character) of argument
Any ideas on how to correct this error? Or any alternate way of going about this?
diversity
indeed needs numerical data, and this may be your problem. What do you get from sum(df[,4:50])
?
Another issue is that you do not need a for()
loop: when given a data frame or a matrix, diversity
will calculate the index for each row (or column if you set argument MARGIN = 2
). So diversity(df[,4:50])
should do, provided that your data are numeric.