2016-09-18 82 views
1

我有這樣的結構中的R[R轉換數據幀手動timeserie

DATA = read.csv("Anomaly.csv") 
DATA 

    col1  col2 
57.17339 0.00064822 
52.90232 0.00064386 
46.20606 0.00064144 
61.23981 0.00064216 

我想這樣

col1  col2  col1-1 col2-1 col1-2 col2-2 
57.17339 0.00064822 NA  NA  NA  NA 
52.90232 0.00064386 57.17339 0.00064822 NA  NA 
46.20606 0.00064144 52.90232 0.00064386 57.17339 0.00064822 
61.23981 0.00064216 46.20606 0.00064144 52.90232 0.00064386 

回答

0

回報我們可以從data.tableshift嘗試。將'data.frame'轉換爲'data.table'(setDT(DATA)),循環訪問Data.table的子集(lapply(.SD, ..), use the shift specifying the n as 0:2. By default the shift has type` as'lag'option。

library(data.table) 
dt <- setDT(DATA)[, unlist(lapply(.SD, shift, n = 0:2), recursive=FALSE)] 

如果我們需要訂購的列

dt[, order(sub("\\D+\\d", "", colnames(dt))), with = FALSE] 
#  col11  col21 col12  col22 col13  col23 
#1: 57.17339 0.00064822  NA   NA  NA   NA 
#2: 52.90232 0.00064386 57.17339 0.00064822  NA   NA 
#3: 46.20606 0.00064144 52.90232 0.00064386 57.17339 0.00064822 
#4: 61.23981 0.00064216 46.20606 0.00064144 52.90232 0.00064386 

或者也可以直接應用於Data.table的子集shift

setDT(DATA)[, shift(.SD, n = 0:2)] 
+1

也可以做'df%>%mutate_all(funs(l1 = lag(。,1),l2 = lag(。,2)))'' –