简体   繁体   English

包含列表的两个data.frame列的相交值

[英]Intersect value of two data.frame columns containing lists

I have a data.frame with 2 colums containing list of values: 我有一个包含2个列的data.frame包含值列表:

    names.t.      l1      l2
  1       x1    1, 0 1, 2, 0
  2       x2 1, 2, 0    1, 0

I would like to add a column to this data.frame that would give me the intersect of l1 and l2 values (as per the intersect set function). 我想在这个data.frame中添加一个列,它会给出l1和l2值的交集(根据交集集函数)。 No for loops would be nice :) 不用循环会很好:)

In the above case, the expected result would be: 在上述情况下,预期结果将是:

  names.t.      l1      l2    inters
1       x1    1, 0 1, 2, 0    1,0
2       x2 1, 2, 0    1, 0    1,0

To reproduce, use code the code below to load the original data.frame in s: 要重现,请使用下面的代码代码在s中加载原始data.frame:

s <- structure(list(names.t. = structure(1:2, .Label = c("x1", "x2"
), class = "factor"), l1 = structure(list(x1 = list("1", "0"), 
    x2 = c("1", "2", "0")), .Names = c("x1", "x2")), l2 = structure(list(
    x1 = list("1", "2", "0"), x2 = c("1", "0")), .Names = c("x1", 
"x2"))), .Names = c("names.t.", "l1", "l2"), row.names = c(NA, 
-2L), class = "data.frame")

You can use Map with interesect : 你可以使用Map with interesect

s$inters <- Map(intersect, s$l1, s$l2)

#   names.t.      l1      l2 inters
# 1       x1    1, 0 1, 2, 0   1, 0
# 2       x2 1, 2, 0    1, 0   1, 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM