To ease reproducibility, I am using the goats
data set from the ResourceSelection package which has spatial data for used (STATUS == 1
) and 'available' (STATUS == 0
) GPS locations of mountain goats. ID
is for individual (n = 10) and ELEVATION
, ... , TASP
are attributes of the points.
library(ResourceSelection)
head(goats)
STATUS ID ELEVATION SLOPE ET ASPECT HLI TASP
1 1 1 651 38.5216 35.3553 243.1131 0.9175926 0.9468804
2 1 1 660 39.6927 70.7107 270.0000 0.8840338 0.6986293
3 1 1 316 20.5477 50.0000 279.2110 0.7131423 0.5749115
4 1 1 334 34.0783 35.3553 266.1859 0.8643775 0.7447368
5 1 1 454 41.6187 25.0000 258.3106 0.9349181 0.8292587
6 1 1 343 28.4694 103.0776 237.0426 0.8254866 0.9756112
I would like to fit a glm
to each individual grouped by Season
(created below) but have the model structure vary according to season. I have been using a number of helpful SO posts and other resources but they all fit a single model to each group where as I would like to fit different models for each Season
grouping.
#Add a new `Season` field
library(tidyverse)
goats <- goats %>%
mutate(Season = if_else(ID %in% 1:3, "Summer",
if_else(ID %in% 4:7, "Winter", "Fall")))
Below I create a model building function and specify the model specific to each season using if else
.
SeasonalMods <- function(df) {
#Models for Archery
if(Season == "Summer") {
glm(STATUS ~ SLOPE + I(SLOPE^2), data = df)
#Models for Winter
} else if (Season == "Winter") {
glm(STATUS ~ SLOPE + ASPECT + TASP, data = df)
#Models for Fall
} else if (Season == "Fall") {
glm(STATUS ~ ELEVATION + SLOPE + ET + ASPECT + HLI + TASP, data = df)}
}
I then try to map the function to the grouped data and create new list-columns as follows.
ModelFits <- goats %>%
group_by(Season, ID) %>%
nest() %>%
mutate(fits = map(data, SeasonalMods),
tidied = map(fits, tidy),
glanced = map(fits, glance),
augmented = map(fits, augment))
Which generates the following error:
Error in mutate_impl(.data, dots) :
Evaluation error: object 'Season' not found
I am not sure how to correctly specify Season
in the SeasonalMods
function so that it is interpretable by map()
.
I tried to add df$
in front of Season
within the if
and else if
statements, but this also generates an error.