I have a dataframe like this one:
library(lubridate)
set.seed(23)
date_list = seq(ymd('2000-01-15'),ymd('2010-09-18'),by='day')
testframe = data.frame(Date = date_list)
testframe$Day = substr(testframe$Date, start = 6, stop = 10)
testframe$ABC = rnorm(3900)
testframe$DEF = rnorm(3900)
testframe$GHI = seq(from = 10, to = 25, length.out = 3900)
testframe$JKL = seq(from = 5, to = 45, length.out = 3900)
I want to have an automatic rolling subset of this dataframe, that should be like this:
testframe_ABC = testframe[,c("Date","Day","ABC")]
testframe_DEF = testframe[,c("Date","Day","DEF")]
testframe_GHI = testframe[,c("Date","Day","GHI")]
testframe_JKL = testframe[,c("Date","Day","JKL")]
The columns Date and Day should always stay, the other columns should be added individually. The name of the varying column should be added to the dataframename, to have a new df. All dataframes could also be in a list of dataframes, if possible.
Any ideas how to do that?
I assume you want a list of 4 data frames whose components are ABC
, DEF
, etc. It would be better to put them in a list:
L <- Map(function(nm) testframe[c("Date", "Day", nm)], names(testframe)[-(1:2)])
in which case L$ABC
or L[[1]]
will refer to the ABC
data frame but if you want to leave them dangling in the global environment this will copy the list components to it:
list2env(L, .GlobalEnv)
I would not use the term rolling
in this context. Typically that term refers to a sliding window such as this:
library(zoo)
rollmeanr(1:10, 3) # 2 is mean of 1:3, 3 is mean of 2:4, etc.
## [1] 2 3 4 5 6 7 8 9