数据框的滚动列减法

时间:2019-06-13 13:38:09

标签: r dataframe subset multiple-columns subtraction

我有一个像这样的数据框:

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)

我想要这个数据帧的自动滚动子集,应该像这样:

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")]

日期和日期列应始终保留,其他列应单独添加。变化列的名称应添加到dataframename中,以具有新的df。如果可能的话,所有数据框也可以在数据框列表中。

有什么想法怎么做?

2 个答案:

答案 0 :(得分:1)

我假设您想要一个包含4个数据帧的列表,这些数据帧的组成为ABCDEF等。最好将它们放在列表中:

L <- Map(function(nm) testframe[c("Date", "Day", nm)], names(testframe)[-(1:2)])

在这种情况下,L$ABCL[[1]]将引用ABC数据框,但是如果要将它们悬在全局环境中,则会将列表组件复制到其中: / p>

list2env(L, .GlobalEnv)

在这种情况下,我不会使用术语rolling。通常,该术语指的是这样的滑动窗口:

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

答案 1 :(得分:1)

您可以使用split.default对每一列进行拆分,然后将{2}的前两列cbind分解为每个元素,即

lapply(split.default(testframe[-c(1, 2)], seq_along(testframe)[-c(1, 2)]), function(i)
                                                cbind.data.frame(testframe[c(1, 2)], i))

给出一个列表,

$`3`
        Date   Day        ABC
1 2000-01-15 01-15  0.1932123
2 2000-01-16 01-16 -0.4346821
3 2000-01-17 01-17  0.9132671

$`4`
        Date   Day       DEF
1 2000-01-15 01-15 1.7933881
2 2000-01-16 01-16 0.9966051
3 2000-01-17 01-17 1.1074905

$`5`
        Date   Day  GHI
1 2000-01-15 01-15 10.0
2 2000-01-16 01-16 17.5
3 2000-01-17 01-17 25.0

$`6`
        Date   Day JKL
1 2000-01-15 01-15   5
2 2000-01-16 01-16  25
3 2000-01-17 01-17  45

已使用数据

dput(testframe)
structure(list(Date = structure(c(10971, 10972, 10973), class = "Date"), 
    Day = c("01-15", "01-16", "01-17"), ABC = c(0.193212333898146, 
    -0.434682108206693, 0.913267096589322), DEF = c(1.79338809206353, 
    0.996605106833546, 1.10749048744809), GHI = c(10, 17.5, 25
    ), JKL = c(5, 25, 45)), row.names = c(NA, -3L), class = "data.frame")