0

Hi I am trying to multiply a column with multiple other columns in my dataset. I am trying to use a loop but it doesn't work. The code returns a warning message but does not create the desired variables

for (i in 1951:2010) {
  data$reg2_year_[i] <- data$reg_2 * data$year_[i]
}

I was expecting it to create the variables: reg2_year_1951...reg2_year_2010

  • 1
    Use [`[[`](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/Extract) instead of `$`: `data[[paste0("reg2_year_", i]] <- data$reg_2 * data[[paste0("year_", i]]` – zephryl Feb 14 '23 at 01:52
  • 1
    You could also do this all at once with no loop. `year_cols = paste0("year_", 1951:2010)` and `reg_cols = paste0("reg2_year_", 1951:2010)` and then `data[reg_cols] = data$reg_2 * data[year_cols]`. (Using `[` instead of `[[` because we're dealing with multiple columns at once.) – Gregor Thomas Feb 14 '23 at 02:01

0 Answers0