Home > Enterprise >  Subset with only consecutive numbers
Subset with only consecutive numbers

Time:05-14

I want to generate all subset of {1,2,3,4} with only consecutive numbers. (For example I want subset {1}, {1,2} or {2,3,4} but not {2,4}. )

This is what I have been trying:

library(ggm)
p2<-powerset(1:4, sort = TRUE, nonempty = TRUE)
m2<-p2
for (i in 1:length(p2)){
  ifelse(length(p2[[i]]) <2, m2<-m2, ifelse(max(diff(as.numeric(p2[[i]])))>1, m2<-m2[- 
c(i)],m2<-m2))
}

I want to first generate power set of {1,2,3,4} and exclude subsets with inconsecutive numbers. But when I am doing the

m2<-m2[- c(i)]

command in the 2nd ifelse to exclude subsets with inconsecutive numbers, I believe I change the index of power set so I keep getting the wrong subsets as I desired.

Any suggestions on how to do it correctly?

Thanks!

CodePudding user response:

You can get all unique ascending sequences between 1 and 4 in base R with the following one-liner:

apply(which(upper.tri(diag(4), TRUE), TRUE), 1, function(x) x[1]:x[2])
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 1 2
#> 
#> [[3]]
#> [1] 2
#> 
#> [[4]]
#> [1] 1 2 3
#> 
#> [[5]]
#> [1] 2 3
#> 
#> [[6]]
#> [1] 3
#> 
#> [[7]]
#> [1] 1 2 3 4
#> 
#> [[8]]
#> [1] 2 3 4
#> 
#> [[9]]
#> [1] 3 4
#> 
#> [[10]]
#> [1] 4

  • Related