如何比较一组向量以查找它们是否包含共同元素?

huangapple go评论58阅读模式
英文:

How to compare a list of vectors to find whether they contain common elements?

问题

以下是您要的翻译结果:

期望结果:

   a,  b,  c
a, T,  F,  T
b, F,  T,  F
c, T,  F,  T
英文:

I have a list of vectors, with variable lengths. I want to know, for all pairwise vectors, do they contain common information? Below is an example:

The list x has three vectors, a, b, and c. a and c both contain 1, so this comparison should return true. No other comparison should return true. I have tried the following solutions. I thought that outer would be the best approach to this problem, but it currently returns true for all comparisons, which is not my expected result.

xx = list(a = 1,
          b = c(2, 3),
          c = c(1, 4, 6))

outer(xx, xx, "%in%")

outer(xx, xx, function(x, y) x %in% y)

func2 = function(x, y){z = cbind(x, y); z[,1] %in% z[,2]}
outer(xx, xx, func2)


Map("%in%", xx, xx)

Expected result:

   a,  b,  c
a, T,  F,  T
b, F,  T,  F
c, T,  F,  T

答案1

得分: 2

I figured this out - although I don't understand the logic behind this solution.

我弄清楚了 - 尽管我不理解这个解决方案背后的逻辑。

It appears that wrapping the function in Vectorize provides the expected output.

看起来将函数包装在Vectorize中会产生预期的输出。

func3 = function(x, y){any(x %in% y)}
outer(xx, xx, Vectorize(func3))

英文:

I figured this out - although I don't understand the logic behind this solution.

It appears that wrapping the function in Vectorize provides the expected output.

func3 = function(x, y){any(x %in% y)}
outer(xx, xx, Vectorize(func3))

huangapple
  • 本文由 发表于 2023年4月17日 11:01:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定