Without getting into the details of the application, I need to run the FSA::depletion(function) in R on a dataframe where the function needs to run iteratively to find a ‘depletion’ value for X number of rows and then proceed to run the operation on the next X number of rows. A dataframe will look something like this:
df <- data.frame(site = c('site1','site1','site1','site2','site2','site2','site3','site3','site3'),
catch = c(30,10,3,40,12,3,10,3,1),
effort = c(600,550,500,800,800,700,400,425,375))
Normally, I would run something like this to find the depletion value on the each site group:
library(dplyr)
library(FSA)
df %>%
group_by(site) %>%
depletion(catch, effort, method = 'Leslie')
However, it seems as though this function simply won’t work with dplyr
as it won’t recognize ‘catch’ or ‘effort’ as vectors from df
. The function seems to only be able to run when using the dataframe$vector
notation such as the following:
depletion(df$catch, df$effort, method = 'Leslie')
Would anyone be able to suggest a way to make this work or a workaround? My next thought would be to add a count column and run the whole thing as a for loop but that sounds like a bad process to make this work.
You could do something like this:
library(purrr)
res <- df %>%
nest_by(site) %>%
mutate(d = list(depletion(data$catch, data$effort, method = 'Leslie')))
You still have to decide how to unpack the results/which bits you want to save: res$d
is a list, if you look at res$d[[1]]
you can see that it’s a complicated object with a lot of components.
You can use the broom
package to tidy the output into your data frame:
library(FSA)
library(dplyr)
library(broom)
df %>%
nest_by(site) %>%
mutate(d = list(depletion(data$catch, data$effort, method = 'Leslie')),
No=list(summary(d, parm="No")),
q=list(summary(d, parm="q"))) %>%
unnest(col=c(No, q))
Gives:
# A tibble: 3 × 5
# Groups: site [3]
site data d No[,1] [,2] q[,1] [,2]
<chr> <list<tibble[,2]>> <list> <dbl> <dbl> <dbl> <dbl>
1 site1 [3 × 2] <depletin> 46 0.818 0.00109 0.0000315
2 site2 [3 × 2] <depletin> 57.0 0.131 0.000878 0.00000334
3 site3 [3 × 2] <depletin> 14.3 0.308 0.00174 0.0000617
Where the second columns of No
and q
are the standard errors, and
df %>%
nest_by(site) %>%
mutate(d = list(depletion(data$catch, data$effort, method = 'Leslie')),
lm = list(tidy(d$lm))) %>%
unnest(col=lm)
Gives
# A tibble: 6 × 8
# Groups: site [3]
site data d term estimate std.error statistic p.value
<chr> <list<tibble[,2]>> <list> <chr> <dbl> <dbl> <dbl> <dbl>
1 site1 [3 × 2] <depletin> (Intercept) 0.0502 0.000909 55.2 0.0115
2 site1 [3 × 2] <depletin> K -0.00109 0.0000315 -34.6 0.0184
3 site2 [3 × 2] <depletin> (Intercept) 0.0500 0.000126 396. 0.00161
4 site2 [3 × 2] <depletin> K -0.000878 0.00000334 -263. 0.00242
5 site3 [3 × 2] <depletin> (Intercept) 0.0249 0.000584 42.6 0.0149
6 site3 [3 × 2] <depletin> K -0.00174 0.0000617 -28.2 0.0226