Angel Lordan Angel Lordan - 2 months ago 10
R Question

R convert data frame to manual timeserie

I Have this structure in R

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

col1 col2
57.17339 0.00064822
52.90232 0.00064386
46.20606 0.00064144
61.23981 0.00064216


i would like a return like this

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

Answer

We can try with shift from data.table. Convert the 'data.frame' to 'data.table' (setDT(DATA)), loop through the Subset of Data.table (lapply(.SD, ..)), use theshiftspecifying thenas 0:2. By default theshifthastype` as "lag" option.

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

If we need to order the columns

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

Or shift can also be directly applied on the Subset of Data.table.

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