I am trying to use purrr::map
to iteratively map over different groups within a data.frame (e.g. summer vs winter surveys), and calculate species accumulation indices by each group (by summer/winter).
# Make some fake data
df <- data.frame(season = c("summer", "summer", "summer",
"winter", "winter", "winter"),
sp_1 = c(7, 11, 6,
0, 0, 0),
sp_2 = c(29, 13, 19,
0, 0, 1),
sp_3 = c(1, 0, 0,
0, 0, 0)
)
# Attempt to split df by summer/winter (season column) and iteratively calculate species accumulation indices.
# While it appears the 'group_by' and 'nest' does split the df,
# applying the 'map' code seems to be working on the entire df (calculates indices NOT by season).
sac_by_group <- df %>%
# Which groups do you want different SAC's for?
dplyr::group_by(season) %>%
# Splits the data into the different groups
tidyr::nest() %>%
# Run the species accumulation curves by group
dplyr::mutate(data = purrr::map(data,
~ vegan::poolaccum(df[,2:4]))) %>%
# Extract the observed species richness estimator (denoted by S)
dplyr::mutate(data_df = purrr::map(data,
~ data.frame(summary(.)$S,
check.names = FALSE))) %>%
# Drop unnecessary columns
dplyr::select(-c(data)) %>%
# Convert the lists back into a data frame
unnest(cols = c(data_df))
sac_by_group
(1) How are my accumulation curves being calculated for the entire dataset, instead of by groups as intended?
(2) How do I solve this issue?
dplyr::mutate(data = purrr::map(data, ~vegan::poolaccum(df[,2:4])))
is referring to the originaldf
and not thedata
column.It should be
I also had to set
minsize = 2
otherwise it would error.