jacquard jacquard - 3 months ago 31
R Question

R data table : Shifting rows of list type

I have a data.table with a

list
type:

x = data.table(k = seq(1:5), l = list(c(4,5)))
> x
k l
1: 1 4,5
2: 2 4,5
3: 3 4,5
4: 4 4,5
5: 5 4,5


I am now trying to shift the
l
values by
1
:

x[, m:=shift(l, 1)]
> x
k l m
1: 1 4,5 NA, 4
2: 2 4,5 NA, 4
3: 3 4,5 NA, 4
4: 4 4,5 NA, 4
5: 5 4,5 NA, 4


This produces a shift 'within' the list, and not across lists.(Aside: It's not clear why
NA
appears for rows
2-5
.)
Whats the way out to get something like this:

x[magic]
> x
k l m
1: 1 4,5 NA
2: 2 4,5 4,5
3: 3 4,5 4,5
4: 4 4,5 4,5
5: 5 4,5 4,5

Answer

You could use a manual shift, like the following.

x[, m := c(NA_real_, head(l, -1L))]

resulting in

   k   l   m
1: 1 4,5  NA
2: 2 4,5 4,5
3: 3 4,5 4,5
4: 4 4,5 4,5
5: 5 4,5 4,5

For a larger shift, you could roll your own function.

mshift <- function(var, n) c(NA[1:n], head(var, -n))

Then use it to shift two places.

x[, m := mshift(l, 2)]

which gives, from the original data

   k   l   m
1: 1 4,5  NA
2: 2 4,5  NA
3: 3 4,5 4,5
4: 4 4,5 4,5
5: 5 4,5 4,5

Obviously, this function is very basic and only shifts to the right (down). If you wanted to, you could adjust the function to shift in the opposite direction and add some class checking/matching as well.

Comments