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

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

问题描述

我在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 ..请参阅安装说明 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

c $ c> foo 为列表中的每个组。注意,它返回一个列表,它可以很好地与:= 如上所示..如果你不添加/ 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天全站免登陆