denis
denis

Reputation: 5673

how to feed a deparse parse sequence with text instead of expression ? denominator entry of ipwpoint function

I am facing a problem when using ipwpoint function from ipw package. Here is a working example with the function ipwpoint:

library(ipw)
df <- data.frame(ttt = sample(0:1,500,replace = T),
                 cofounder1 = rnorm(500),
                 cofounder2 = rnorm(500))

ipwt <- ipwpoint(
  exposure = ttt ,
  family = "binomial",
  link = "logit",
  numerator = ~ 1,
  denominator = ~cofounder1 + cofounder2 ,
  data = df
)

Suppose now that I want to define the same regression, but with the denominator coming from a vector of variable names

vars <- c("cofounder1","cofounder2")

I thought I could use a formula:

formula <- as.formula(paste0("~",paste0(vars,collapse = "+")))
ipwt <- ipwpoint(
  exposure = ttt ,
  family = "binomial",
  link = "logit",
  numerator = ~ 1,
  denominator = formula,
  data = df
)

But this does not work:

Error in eval(parse(text = paste(deparse(tempcall$exposure, width.cutoff = 500), : object 'tttformula' not found

because what the function does is that is deparse an expression to then paste it with the exposure, and parse it again and evaluate it, see https://github.com/cran/ipw/blob/master/R/ipwpoint.R#L87. So it pastes "formula" instead of the actual formula.

Using text does not work either:

ipwt <- ipwpoint(
  exposure = ttt ,
  family = "binomial",
  link = "logit",
  numerator = ~ 1,
  denominator = paste0("~",paste0(vars,collapse = "+")),
  data = df
)

How can I do to define my regression from the c("cofounder1","cofounder2") vector ?

Upvotes: 1

Views: 171

Answers (1)

mfalco
mfalco

Reputation: 450

What about parsing the whole function call as string?:

function_call<-paste0("ipwt <- ipwpoint(
  exposure = ttt ,
  family = \"binomial\",
  link = \"logit\",
  numerator = ~ 1,
  denominator = ~",vars[1]," + ",vars[2]," ,
  data = df
)")

eval(parse(text = function_call))

Upvotes: 1

Related Questions