按组移动 data.table 中的一列列表 [英] Shift a column of lists in data.table by group

查看:24
本文介绍了按组移动 data.table 中的一列列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 R 中有一列列表:

I have a column of lists in R:

DT <- data.table(foo = c(list(c("a","b","c")), list(c("b","c")), list(c("a","b")), list(c("a"))), id = c(1,1,2,2))
DT
     foo id
1: a,b,c  1
2:   b,c  1
3:   a,b  2
4:     a  2

我想做的是复制典型的换班行为来获得:

What I would like to do is replicate typical shift behavior to get:

     foo id
1:   b,c  1
2:    NA  1
3:     a  2
4:    NA  2

对于普通列,我会使用 shift,但这会将列表拆分为列并移动这些列(并标记警告):

For a normal column I would use shift, but this splits the lists into columns and shifts those (and flags a warning):

DT[ , shift(foo,1,type = "lead"), by = id]
   id V1 V2
1:  1  b  c
2:  1  c NA
3:  1 NA  c
4:  2  b NA
5:  2 NA NA

如果我将 shift 调用包装到一个列表中,则返回的是一个列表,但只有向量元素被移动了:

If I wrap the shift call into a list, the return is a list but only the vector elements have been shifted:

DT[ , list(shift(foo,1,type = "lead")), by = id]
   id     V1
1:  1 b,c,NA
2:  1   c,NA
3:  2   b,NA
4:  2     NA

推荐答案

出现了 不止一次.所以我继续并添加了这个功能.不过,您目前必须使用开发版本,v1.9.7 .. 请参阅安装说明 这里.

This has come up more than once. So I've gone ahead and added this feature. You'll have to use the development version at the moment though, v1.9.7.. see installation instructions here.

DT[, foo2 := shift(.(foo), type = "lead"), 
       by = id]
#      foo id foo2
# 1: a,b,c  1  b,c
# 2:   b,c  1   NA
# 3:   a,b  2    a
# 4:     a  2   NA

只需为 list 中的每个组包装 foo.请注意,它返回一个 list-of-list:= 配合使用,如上所示.如果您不添加/更新您的 data.table('没有多大意义),那么你将不得不提取列表元素.

Just wrap foo for each group in a list. Note that it returns a list-of-list which works well with := as shown above.. If you're not adding/updating your data.table (which doesn't make much sense), then you'll have to extract the list element.

DT[, .(foo2 = shift(.(foo), type="lead")[[1L]]), 
        by = id]
#    id foo2
# 1:  1  b,c
# 2:  1   NA
# 3:  2    a
# 4:  2   NA

shift() 旨在与 data.table 的 := 语法完美配合,因为它始终返回相同数量的行.

shift() is designed to play nicely with data.table's := syntax, since it returns the same number of rows all the time.

这篇关于按组移动 data.table 中的一列列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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