rbchan / unmarked

R package for hierarchical models in ecological research
https://rbchan.github.io/unmarked/
36 stars 25 forks source link

formatMult no longer corrupts covariates when factors are present; fixes #47 #87

Closed adamdsmith closed 8 years ago

adamdsmith commented 8 years ago
library(plyr); library(dplyr)
test <- expand.grid.df(expand.grid(site = LETTERS[1:10], visit = 1:3), 
                       data.frame(year = 2010:2012)) %>% arrange(site, year, visit) %>%
                       select(year, site, visit)
test <- test %>% mutate(
  y  = rpois(nrow(test), lambda = 2),
  ocov = rnorm(nrow(test)),
  scov = 2 * as.numeric(test$site),
  yscov = 1.3 * as.numeric(interaction(test$site, test$year)))

# All continuous
nofac <- formatMult(test)
str(nofac)

# Add factor variables to each group of variables (obsCovs, siteCovs, yearlysiteCovs)
test2 <- test %>% mutate(
  obsfac = factor(sample(LETTERS[1:2], nrow(test), replace = TRUE)),
  sitefac = factor(round_any(as.numeric(site), 5)),
  ysfac = factor(round_any(as.numeric(interaction(site, year)), 10))
)

withfac <- formatMult(test2) 
str(withfac)

# Only factor variables for each group variables (obsCovs, siteCovs, yearlysiteCovs)
test3 <- select(test2, -ocov, -scov, -yscov)
onlyfac <- formatMult(test3)
str(onlyfac)

(fm <- colext(~scov, ~1, ~1, ~ocov, nofac)) 
(fm2 <- colext(~scov + sitefac, ~1, ~1, ~ocov + obsfac + ysfac, withfac))  
(fm3 <- colext(~sitefac, ~1, ~1, ~obsfac + sitefac + ysfac, onlyfac))  
rbchan commented 8 years ago

Great, thanks. Could you add a unit test? It's the best way I know of to keep unmarked bug free.

adamdsmith commented 8 years ago

Done. Sorry, I'll assume that's the case from here on out...