英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论