R数据表:移动列表类型的行 [英] R data table : Shifting rows of list type

查看:66
本文介绍了R数据表:移动列表类型的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有列表类型的data.table:

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

我现在试图将 l $ 1 的价值:

  := shift(1,1)] 
> x
klm
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

(aside:不清楚为什么 NA 出现在行 2-5 。)
获得类似这样的东西的方法:

  x [magic] 
> x
klm
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


解决方案

您可以使用手动移位,如下所示。

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

导致


  klm 
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


对于较大的移位,您可以滚动自己的函数。

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

然后使用它移动两个地方。

  ,m:= mshift(1,2)] 

>


  klm 
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


显然,这个函数非常基本,只向右移动。如果你想,你可以调整功能向相反的方向移动,并添加一些类检查/匹配。


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

解决方案

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.

这篇关于R数据表:移动列表类型的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆