Reputation: 1711
I have a model.
library(dlnm)
library(splines)
data(chicagoNMMAPS)
cb1.pm <- crossbasis(chicagoNMMAPS$pm10, lag=15, argvar=list(fun="lin"),
arglag=list(fun="poly",degree=4))
model1 <- glm(death ~ cb1.pm + ns(time, 7*14) + dow,
family=quasipoisson(), chicagoNMMAPS)
pred1.pm1 <- crosspred(cb1.pm, model1, bylag=0.2, cumul=TRUE)
I want to use a character vector to call the object cb1.pm
so I tried this.
# use character vector
i = 'pm'
cb1.var = paste0('cb1.', i) %>% get()
model2 <- glm(death ~ cb1.var + ns(time, 7*14) + dow,
family=quasipoisson(), chicagoNMMAPS)
pred1.pm2 <- crosspred(cb1.pm, model2, bylag=0.2, cumul=TRUE) # Error occur here
identical(cb1.pm, cb1.var) # TRUE
The result identical(cb1.pm, cb1.var)
is TURE
, but
why can't these two variables replace each other?
Any help will be highly appreciated!
Upvotes: 0
Views: 55
Reputation: 173793
The problem is that crosspred
uses non-standard evaluation to extract the name of the first argument from your call and tries to match it up to the variables in model2
. It does this using grep
. Since you have used cb1.var
as the name in your model, the crosspred
function doesn't find any coefficients containing the string "cb1.pm" and throws an error.
The way round this is to ensure that cb1.var
remains as a symbol and is substituted for cb1.pm
before the model is built. This is also more efficient, since you don't need to copy the whole cb1.pm
data:
i = 'pm'
cb1.var = paste0('cb1.', i)
form <- as.formula(paste("death ~", cb1.var, "+ ns(time, 7*14) + dow"))
model2 <- glm(form, family = quasipoisson(), chicagoNMMAPS)
pred1.pm2 <- crosspred(cb1.pm, model2, bylag = 0.2, cumul=TRUE)
We no longer get a warning, and we can confirm we have the correct model:
identical(pred1.pm1, pred1.pm2)
#> [1] TRUE
Upvotes: 1