Page 1 of 1

Coding for empty levels in grouping factors

PostPosted: Thu Oct 29, 2015 8:57 am
by Phil Chapman
Hi all,

A quick question about levels in factor covariates used as groups in my secr model.
I want to run a multisession model with a covariate (=species) for which not all levels are present every session (=trapping year). In other words, for some species I didn't catch any in some years.

In the data entry guidance pdf, it says that ordinarily levels for factor covariates have to be equal across sessions, and if you want to override this then you have to specify the levels manually.

I've tried adding something like
Code: Select all
levels=c("species1", "species2", "species3")
to the arguments of
Code: Select all
read.capthist
but with no success-it ignores the addition and fails to create the capthist properly.

Am I going about this the wrong way? Sorry if this is a rather idiot question, I'm a relative R novice and this seemed like the intuitive step.

Re: Coding for empty levels in grouping factors

PostPosted: Thu Oct 29, 2015 7:33 pm
by murray.efford
Not an idiot question at all, in fact you have put your finger on a place in the documentation where I just waved my hands instead of providing a concrete solution. As I remember, the solution is manual and ugly, i.e. you have to massage the covariates to impose a uniform set of factor levels. Here is one way -

Code: Select all
library(secr)

## For demonstration purposes, let's mess up the ovenbird data
lapply(covariates(ovenCH), function(x) levels(x$Sex))
lapply(covariates(ovenCH), function(x) table(x$Sex))

## throw out all females from first year, manually drop level 'F'
ovenCH[[1]] <- subset(ovenCH[[1]], covariates(ovenCH[[1]])$Sex == 'M')
covariates(ovenCH[[1]])$Sex <- factor(covariates(ovenCH[[1]])$Sex)
lapply(covariates(ovenCH), function(x) levels(x$Sex))
verify(ovenCH)

## So we now have a bad CH.
## Let's fix it.

for (i in 1:length(ovenCH))
    covariates(ovenCH[[i]])$Sex <- factor(covariates(ovenCH[[i]])$Sex,
    levels = c('F','M'))

## all OK again:
lapply(covariates(ovenCH), function(x) levels(x$Sex))
verify(ovenCH)
summary(ovenCH, terse=T)


Murray

Re: Coding for empty levels in grouping factors

PostPosted: Tue Nov 03, 2015 5:37 pm
by Phil Chapman
Thanks Murray!