Решение, однако, glmer не запускается, потому что вектор присутствия не включен в пример данных:
# Install pacakges if they are not already installed: necessary_packages => character vector
necessary_packages <-
c("lme4")
# Create a vector containing the names of any packages needing installation:
# new_pacakges => character vector
new_packages <- necessary_packages[!(necessary_packages %in%
installed.packages()[, "Package"])]
# If the vector has more than 0 values, install the new pacakges
# (and their) associated dependencies: varied => stdout
if (length(new_packages) > 0) {
install.packages(new_packages, dependencies = TRUE)
}
# Initialise the packages in the session: bool => stdout
lapply(necessary_packages, require, character.only = TRUE)
# Append a grouping vector to df thats values
# a concatenation of idAnimal and a downsampled date vec: group => character vector
df$group <- paste(df$idAnimal,
gsub("\\s+|[[:punct:]]", "_",
gsub(" .*", "", df$date)),
sep = "_")
# Allocate some memory by building an empty list the same length
# as the number of unique group values: df_list => list
df_list <- vector("list", length(unique(df$group)))
# Replicate the list in order to store the results of glm:
# glm_res_list => list
glm_res_list <- df_list
# Store each animalID day subset: df_list => list
df_list <- split(df, df$group)
# Run an lme4 glmer model on each list element, store the result
# in glm_res_list: glm_res_list => list
# Note: not run as Presence vector is not included in sample data
glm_res_list <- lapply(df_list, function(x){
glmer(Presence~ Distance * sex + elevation* sex + (1 |park),
family = binomial,
data = x)
}
)
Данные:
df <- structure(
list(
idAnimal = c(
"animal1",
"animal1",
"animal1",
"animal1",
"animal1",
"animal1",
"animal1",
"animal1",
"animal1",
"animal1",
"animal2",
"animal2",
"animal2",
"animal2",
"animal2",
"animal2",
"animal3",
"animal3",
"animal3",
"animal3",
"animal3"
),
date = structure(
c(
1535724000,
1535767200,
1535788800,
1535810400,
1535832000,
1535853600,
1535875200,
1535896800,
1535940000,
1535961600,
1535983200,
1536004800,
1536026400,
1536048000,
1536069600,
1536091200,
1536112800,
1536134400,
1536156000,
1536177600,
1536220800
),
class = c("POSIXct",
"POSIXt"),
tzone = "Australia/Sydney"
),
elevation = c(
2376L,
2402L,
2366L,
2402L,
2428L,
2376L,
2354L,
2337L,
2334L,
2406L,
2231L,
2343L,
2306L,
2177L,
2206L,
2318L,
2324L,
2259L,
2396L,
2436L,
2380L
),
sex = c(
"M",
"M",
"M",
"M",
"M",
"M",
"M",
"M",
"M",
"M",
"F",
"F",
"F",
"F",
"F",
"F",
"F",
"F",
"F",
"F",
"F"
),
Distance = c(
678L,
1023L,
933L,
239L,
423L,
817L,
1073L,
210L,
967L,
242L,
547L,
506L,
1190L,
1219L,
271L,
142L,
263L,
996L,
54L,
1129L,
811L
)
),
row.names = c(NA,-21L),
class = "data.frame"
)