1

I am trying to create different subsets out of a table and with each iteration I want to shift one column upwards. So far I realized this with this code but undynamically:

subset_cor_lag00 <- subset(data_24h, select = c(price_return, sentiment_return, tweet_return))
korr_tab_lag00 <- cor(subset_cor_lag00)

subset_cor_lag01 <- transform(subset_cor_lag00, price_return = lead(price_return))
subset_cor_lag01 <- na.omit(subset_cor_lag01)
korr_tab_lag01 <- cor(subset_cor_lag01)

But now I tried to do this dynamically but I got stuck with it. So maybe someone has a hint. I really would appreciate it. I tried this

for(i in 1:5) {
  paste0("subset_cor_lag0", i) <- transform(paste0("subset_cor_lag0", i-1), price_return = lead(price_return))
  paste0("subset_cor_lag0", i) <- na.omit(paste0("subset_cor_lag0", i))
  paste0("korr_tab_lag0", i) <- cor(paste0("subset_cor_lag0", i))
}
lmo
  • 37,904
  • 9
  • 56
  • 69
Nico
  • 11
  • 2

1 Answers1

1

You can use assign for this, but usually having sequentially named variables isn't nice to work with. The better way is to use a list:

subset_cor_lag = list(subset(data_24h, select = c(price_return, sentiment_return, tweet_return)))

for(i in 2:6) {
  temp = transform(subset_cor_lag[[i - 1]], price_return = lead(price_return))
  subset_cor_lag[[i]] = na.omit(temp)
}

korr_tab = lapply(subset_cor_lag, cor)


## add names, if desired:
name_vec = paste0("lag", 0:5)
names(subset_cor_lag) = name_vec
names(korr_tab) = name_vec

You can then access, e.g., subset_cor_lag[["lag2"]] or subset_cor_lag[[3]], which is easy to do programmatically in a loop or with lapply.

See my answer at How to make a list of data frames? for more discussion and examples.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294