仅连续数字的子集

发布于 2025-01-28 13:59:14 字数 520 浏览 2 评论 0原文

我想生成只有连续数字的{1,2,3,4}的所有子集。 (例如,我想要子集{1},{1,2}或{2,3,4},而不是{2,4}。)

这是我一直在尝试的:

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))
}

我想首先生成{1的功率集,2,3,4},并排除具有不一致数字的子集。但是,当我在第二IFELSE中执行

m2<-m2[- c(i)]

命令以排除不对符的数字的子集时,我相信我会更改电源集的索引,以便根据需要获得错误的子集。

关于如何正确执行的任何建议?

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的呼吸 2025-02-04 13:59:14

您可以使用以下单线在基础r中获得1到4之间的所有唯一升序序列:

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文