Rahul Kumar Vij
Rahul Kumar Vij

Reputation: 83

Giving a moving sequence to a data set for sequence analysis using R

I have a dataset in R which looks like

x  y
1  a
2  b
3  c
4  d
5  e
6  f
7  g

supposing x as time in minutes and y as items bought in that minute. i want to convert it to 2 minute moving window, each window with a unique id, each item with a minute id in that unique id and items bought in that group.

final result should look like:

x1 x2 x3
1  1  a
1  2  b 
2  1  b
2  2  c
3  1  c
3  2  d
4  1  d
4  2  e
5  1  e
5  2  f
6  1  f
6  2  g

i am able to do it in matlab but not in r

matlab code:

clc
clear all
close all

Time = [1:10].';
Event = ['A':'J'].';


for k = 1:(length(Time)-1)

Gp(k).ID = Time(k,1);
Gp(k).Seq(1,1) = 1;
Gp(k).Seq(2,1) = 2;
Gp(k).Event(1,1) = Event(k,1);
Gp(k).Event(2,1) = Event(k+1,1);


end

Upvotes: 1

Views: 72

Answers (1)

akrun
akrun

Reputation: 886938

We can replicate the sequence of rows, and then do the transformation

df2 <- transform(df1[rep(1:nrow(df1), each = 2),], x1=x, x2 = 1:2)[-(13:14),-(1:2)]
row.names(df2) <- NULL
transform(df2,  x3= c(rbind(df1$y[-nrow(df1)], df1$y[-1])))
#   x1 x2 x3
#1   1  1  a
#2   1  2  b
#3   2  1  b
#4   2  2  c
#5   3  1  c
#6   3  2  d
#7   4  1  d
#8   4  2  e
#9   5  1  e
#10  5  2  f
#11  6  1  f
#12  6  2  g

Upvotes: 1

Related Questions