Home > Software engineering >  Consider formula(paste(x, collapse = " ")) instead
Consider formula(paste(x, collapse = " ")) instead

Time:10-30

My codes:

for (x in dataset$year){
  controls_c <- paste(controls, collapse = " ")
  spec <- formula(paste(dataset$Inflation,
                        "~MonetaryPolicyShockRomer&Romer ",
                        controls_c))
  regs_controls[[x]] <- lm(spec, data = dataset %>% filter(x))
}

And I am having the following error:

Using formula(x) is deprecated when x is a character vector of length > 1. Consider formula(paste(x, collapse = " ")) instead.

How can I solve the issue?

CodePudding user response:

Speculation:

controls_c <- c("somefield", "anotherfield", ...)
regs_controls <- list()
controls_c <- paste(controls, collapse = " ")
for (x in unique(dataset$year)) {
  spec <- formula(paste("Inflation", "~",
                        paste(c("`MonetaryPolicyShockRomer&Romer`", controls_c),
                              collapse = "   ")))
  regs_controls[[as.character(x)]] <- lm(spec, data = dataset %>% filter(year == x))
}

Changes from your code:

  • I've combined your single column "MonetaryPolicyShockRomer&Romer" into a vector along with controls_c so that we can collapse them together into the single RHS of the formula;
  • wrapped that "Monetary..." in backticks, since the & is not otherwise a "legal" character within an object name (i.e., a column name). It is possible to use, you just need to wrap in backticks to be able to use it, in the same fashion that you can have column names entirely of (or starting with) numbers
  • changed the loop so that you're looping only once per unique year found
  • changed the storage of year in the list as a string instead of a number; doing regs_controls[[2021]] <- ..., for instance, will try to store the results from lm(..) in the 2021st position in the list, which is not necessarily what you are going for (I'm inferring). Instead, regs_controls[["2021"]] will be used, which will go into the first available position (depending on how much iterations in the for loop before this year).
  • Related