Calculating Powerset in R

偶尔善良 提交于 2021-01-28 15:19:41

问题


I have to sets A={1,2,3} and B={a,b,c,d,e}. I want the set of subsets of elements from both A and B that contain at least one element of A and one element of B. As clearified here: Cartesian product with all elements, I need to use the following formula:

P(A ∪ B)∖(P(A) ∪ P(B))

In R, I tried the following query:

require(HapEstXXR)

A <- c(1,2,3)
B <- c("A", "B", "C", "D", "E")

setdiff(powerset(union(A,B)), union(powerset(A),powerset(B)))

As as result I got 221 elements. As far as I know, there should be (2^3-1)(2^5-1) = 217 elements.

Is my query wrong?


回答1:


length( s1 <- powerset(union(A,B)) ) #255
length( s2 <- union(powerset(A),powerset(B)) ) # 38

255-38 = 217, which seems to be what you are looking for

However, not all of s2 are contained in s1

setdiff(s2, s1)
# 8 sets to create.
# 32 sets to create.
# 256 sets to create.
# [[1]]
# [1] 1 2
# 
# [[2]]
# [1] 1 3
# 
# [[3]]
# [1] 2 3
# 
# [[4]]
# [1] 1 2 3

These 4 elements explain the difference beween 221 and 217




回答2:


Don't mix classes:

length( z <- setdiff(powerset(union(A,B)), union(powerset(as.character(A)),powerset(B))) ) 
# 217

Notice that as.character is applied to A.



来源:https://stackoverflow.com/questions/31185513/calculating-powerset-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!