如何处理data.table中的列的列 [英] How to handle columns of lists in data.table

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

问题描述

在合并数据的过程中,我经常会遇到列表的列(例如左表中的一行在右表中有几个匹配项)。

In the process of merging data I often end up with columns of lists (for example a line in a left table has several matches in a right table)

DT = data.table(x=list(c(1,2),c(3,4,5)),y=list(c(T,T),c(T,F,T)),z=c(1,2),N=c(1L,2L))
#       x               y z N
#1:   1,2       TRUE,TRUE 1 1
#2: 3,4,5 TRUE,FALSE,TRUE 2 2




  1. 是否可以现场修改更新 code>到 x [y]

  1. Is it possible to modify in-place aka update x to x[y] ?



它不会更新(看起来很丑陋)为:

I can do it but not updating (and it looks ugly) as:

DT1 = DT[,list(x=list(unlist(x)[unlist(y)])),by=N]
DT = cbind(DT[,x:=NULL],DT1[,list(x)])
                 y z N   x
1:       TRUE,TRUE 1 1 1,2
2: TRUE,FALSE,TRUE 2 2 3,5

现在让我们定义 mySet = c(1,5),并且想要检查%mySet中 x%

Now let's suppose I define mySet = c(1,5) and want to check that values of column x %in% mySet


  1. 我如何做?

  1. How can I do this ?

                 y z N   x isInMySet
1:       TRUE,TRUE 1 1 1,2 TRUE,FALSE
2: TRUE,FALSE,TRUE 2 2 3,5 FASLE,TRUE



推荐答案

我为您早期的问题写了一个答案,意识到您已删除了该问题。以下是更新方式(第一部分的答案)。

I wrote an answer for your earlier question to realize that you had deleted the question. Here's how you can update (the answer for your first part).

DT[, x := list(list(unlist(x)[unlist(y)])), by=N]

#      x               y z N
# 1: 1,2       TRUE,TRUE 1 1
# 2: 3,5 TRUE,FALSE,TRUE 2 2

而对于第二部分:

DT[, isInMySet := list(list(unlist(x) %in% mySet)), by=N]

#      x               y z N  isInMySet
# 1: 1,2       TRUE,TRUE 1 1 TRUE,FALSE
# 2: 3,5 TRUE,FALSE,TRUE 2 2 FALSE,TRUE

(或者)

DT[, isInMySet := lapply(x, function(x) x %in% mySet)]

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

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