基于类型列表列中的值的子集data.table [英] Subset data.table based on value in column of type list

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

问题描述

所以我目前有一种类型为list的data.table的情况. 该列表可以包含不同的值,其中NULL以及其他可能的值. 我试图对data.table进行子集化,以仅保留此列的值为NULL的行.

So I have this case currently of a data.table with one column of type list. This list can contain different values, NULL among other possible values. I tried to subset the data.table to keep only rows for which this column has the value NULL.

瞧瞧……我在下面的尝试(例如,我将列命名为"ColofTypeList"):

Behold... my attempts below (for the example I named the column "ColofTypeList"):

DT[is.null(ColofTypeList)]

它向我返回Empty data.table.
然后我尝试了:

It returns me an Empty data.table.
Then I tried:

DT[ColofTypeList == NULL] 

它返回以下错误(我预期是错误):

It returns the following error (I expected an error):

Error in .prepareFastSubset(isub = isub, x = x, enclos = parent.frame(),  : 
  RHS of == is length 0 which is not 1 or nrow (96). For robustness, no recycling is allowed (other than of length 1 RHS). Consider %in% instead.

(精确地说,我的原始data.table包含96行,这就是为什么错误消息说出这样的话:

(Just a precision my original data.table contains 96 rows, which is why the error message say such thing:

不是1或nrow(96).

which is not 1 or nrow (96).

行数不是重点.
然后我尝试了这个:

The number of rows is not the point).
Then I tried this:

DT[ColofTypeList == list(NULL)]

它返回以下错误:

Error: comparison of these types is not implemented

我还尝试给出一个长度与列长度相同的列表,并得到了同样的最后一个错误.

I also tried to give a list of the same length than the length of the column, and got this same last error.

所以我的问题很简单:将"ColofTypeList"的元素为NULL的行进行子集化的正确data.table方法是什么?

So my question is simple: What is the correct data.table way to subset the rows for which elements of this "ColofTypeList" are NULL ?

这是一个可复制的示例

DT<-data.table(Random_stuff=c(1:9),ColofTypeList=rep(list(NULL,"hello",NULL),3))

玩得开心!

推荐答案

如果它是list,我们可以遍历列表并应用is.null返回逻辑vector

If it is a list, we can loop through the list and apply the is.null to return a logical vector

DT[unlist(lapply(ColofTypeList, is.null))]
#   ColofTypeList anotherCol
#1:                        3

或者另一个选择是lengths

DT[lengths(ColofTypeList)==0]

数据

DT <- data.table(ColofTypeList = list(0, 1:5, NULL, NA), anotherCol = 1:4)

这篇关于基于类型列表列中的值的子集data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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