user2354204
user2354204

Reputation:

Reshape of Time series in R

I have a data.frame like the following

   Values
1  16.50
2  16.53
3  16.48
4  16.38
5  16.16
6  16.10
7  16.21
8  16.50

I need to create a new data frame that contains, for each value, the previous 2 record in the same row, for example:

 line #1: 16.50, 16.53, 16.48
 line #2: 16.53, 16.48, 16.38

Have you got any suggestion on how achieve the result?

Thank you in advance.

Upvotes: 0

Views: 110

Answers (3)

David Arenburg
David Arenburg

Reputation: 92282

You could define a helper function

lagfunc <- function(x, y) unname(cbind(y, sapply(seq_len(x), function(x) c(tail(y, -x), rep(NA, x)))))

Then run it

n <- 2
lagfunc(n, df$Values)
#       [,1]  [,2]  [,3]
# [1,] 16.50 16.53 16.48
# [2,] 16.53 16.48 16.38
# [3,] 16.48 16.38 16.16
# [4,] 16.38 16.16 16.10
# [5,] 16.16 16.10 16.21
# [6,] 16.10 16.21 16.50
# [7,] 16.21 16.50    NA
# [8,] 16.50    NA    NA

Or using data.table

library(data.table)
setDT(df)[, shift(Values, 0:n, type = "lead")]

Upvotes: 2

akrun
akrun

Reputation: 886978

Try

library(dplyr)
df %>%
    mutate(Col1=lead(Values,1), Col2=lead(Values,2))
# Values  Col1  Col2
#1  16.50 16.53 16.48
#2  16.53 16.48 16.38
#3  16.48 16.38 16.16
#4  16.38 16.16 16.10
#5  16.16 16.10 16.21
#6  16.10 16.21 16.50
#7  16.21 16.50    NA
#8  16.50    NA    NA

Update

Or you could try

n <- 3
m1 <- matrix(df$Values, nrow=nrow(df)+1, ncol=n)[-nrow(df)+1,]
m1
#     [,1]  [,2]  [,3]
#[1,] 16.50 16.53 16.48
#[2,] 16.53 16.48 16.38
#[3,] 16.48 16.38 16.16
#[4,] 16.38 16.16 16.10
#[5,] 16.16 16.10 16.21
#[6,] 16.10 16.21 16.50
#[7,] 16.50 16.50 16.53
#[8,] 16.50 16.53 16.48

data

df <- structure(list(Values = c(16.5, 16.53, 16.48, 16.38, 16.16, 16.1, 
16.21, 16.5)), .Names = "Values", class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

Upvotes: 4

Arun
Arun

Reputation: 118779

You can use the embed function in base R:

embed(DF$Values, 3L)[, 3:1]
#       [,1]  [,2]  [,3]
# [1,] 16.50 16.53 16.48
# [2,] 16.53 16.48 16.38
# [3,] 16.48 16.38 16.16
# [4,] 16.38 16.16 16.10
# [5,] 16.16 16.10 16.21
# [6,] 16.10 16.21 16.50

Upvotes: 4

Related Questions