Home > Back-end >  How could I pass a character value as an offset argument into glm function?
How could I pass a character value as an offset argument into glm function?

Time:07-10

Suppose the dataset, my_data, looks like this

Count Covariate offset_a offset_b
... ... ... ...

while using offset_a as my offset, the below statement would work:

glm(my_formula, data = my_data, family = 'quasipoisson', offset = offset_a)

However, if I want to write a loop that passes offset_a and offset_b sequentially into glm(), I wouldn't be able to simply pass a character value into the offset argument. Like this:

offset_list <- c("offset_a", "offset_b")

for (k in offset_list){
  ...
  fit = glm(my_formula, data = my_data, family = 'quasipoisson', offset = k)
  ...
}

I tried applying noquote() to the offset, as

fit = glm(my_formula, data = my_data, family = 'quasipoisson', offset = noquote(k))

but it doesn't work either.

Does anyone know how to achieve this?

Furtherly,

if we have a character variable,

statement = "glm(my_formula, data = my_data, family = 'quasipoisson', offset = offset_a)"

Is there any way to pass variable, statement, into glm() directly and get the output successfully?

Much Appreciated!

CodePudding user response:

Probably the easiest way to do this is to put the offset term directly into the formula with reformulate:

resp_var <- "y"
form0 <- "var1   var2   var3*var4"
offset_list <- c("offset_a", "offset_b")
for (k in offset_list){
  ...
  form <- reformulate(response = resp_var,
                      c(form0, sprintf("offset(%s)", k)))
  fit <- glm(form, data = my_data, family = 'quasipoisson')
  ...
}

offset = get(k) would probably also work.

CodePudding user response:

You can use this

offset_list <- c("offset_a", "offset_b")
fit <- list()
for (k in 1:length(offset_list)){
    fit[[k]] = glm(my_formula, data = my_data, family = 'quasipoisson',
    offset = get(offset_list[k]))
}
  •  Tags:  
  • r glm
  • Related