[英]data.table - check if one column is in another (list) column
I have a data table with a column containing lists. 我有一个数据表,其中的列包含列表。 I want to check if another column is present in the list column as.
我想检查列表列中是否还有另一列。
library(data.table)
dt <- data.table("a" = 1:3, "b" = list(1:2, 3:4, 5:6))
I tried: 我试过了:
dt[, is_a_in_b := a %in% b]
dt
# a b is_a_in_b
# 1: 1 1,2 FALSE
# 2: 2 3,4 FALSE
# 3: 3 5,6 FALSE
which does not give the correct result. 这不会给出正确的结果。 The desired table would be
所需的表将是
dt
# a b is_a_in_b
# 1: 1 1,2 TRUE
# 2: 2 3,4 FALSE
# 3: 3 5,6 FALSE
You can use the mapply
function with applying the function %in%
to two vectors: a
and b
. 您可以通过将
%in%
函数应用于两个向量来使用mapply
函数: a
和b
。 In effect it takes a pair of vectors (lists) and produces for every index ix
the result of a[ix] %in% b[[ix]]
. 实际上,它采用一对向量(列表)并为每个索引
ix
生成a[ix] %in% b[[ix]]
。
dt[, is_a_in_b := mapply('%in%', a, b)]
> dt
a b is_a_in_b
1: 1 1,2 TRUE
2: 2 3,4 FALSE
3: 3 5,6 FALSE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.