Reputation: 795
I have a data frame like so:
df<- data.frame(plot=c(rep(133, 3), rep(134,4)), plant= c(1,1,2,3,3,4,4),
morpho= c("A", "B", "C", "D","E","B","C"), freq=c(2,1,2,1,3,1,3))
Then I use the following to get the dataframe in a format that is useable for cast()
:
library("reshape")
cast<- cast(df, plot+plant ~ morpho,
value ='freq',fun.aggregate=sum)
which makes it a list of 7 elements.
I now want to apply a function to the each plot to calculate beta diversity among plants in each plot. I would use the function :
library("vegetarian")
d(cast, lev="beta", q=1, boot=TRUE)
I tried the following without success:
lapply(cast, function(x){d(x,lev= "beta", q=1, boot=TRUE)})
The output for this example would be:
output<- data.frame( plot=c(133, 134), D.Value= c(2,2 ), StdErr=c(0, 1.734224e-16) )
Upvotes: 1
Views: 123
Reputation: 887118
We could do this by
library(dplyr)
library(purrr)
split(cast[-(1:2)], cast$plot) %>%
map(d, lev = "beta", q = 1, boot = TRUE) %>%
map(as_tibble) %>%
bind_rows(., .id = 'plot')
If we look at the OP's code, it is looping through each column, where as d
requires 'abundances' as (based on ?d
)
Community data as a matrix where columns are individual species and rows are sites. Matrix elements are abundance data
Therefore, we split
the dataset by the 'plot' on the subset of data i.e. the data with only the count columns, apply the 'd' on each of the list
elements by using map
and then bind the list elements with bind_rows
Upvotes: 1