首页> 疑难解答

R:通过删除和添加循环变量来迭代向量

withpy 2021-06-15

简介考虑一个向量:昏暗

考虑一个向量:

dim <- c("a", "b", "c", "d")

我希望能够通过删除一些变量然后使用更新的向量来创建向量的版本。

例如:

我希望它迭代到可能由此产生的所有可能的向量:

    dim <- c("a", "b", "d")

等等等等。我可以循环或某种程度上这样做,我不必指定任何东西。顺序没关系,所以我不想要a,b,c和c,a,b

1
投票

您可以通过以下方式获得:

dim <- c("a", "b", "c", "d")
> Map(combn, list(dim), 1:length(dim))

[[1]]  # All combinations of size 1
     [,1] [,2] [,3] [,4]
[1,] "a"  "b"  "c"  "d" 

[[2]]  # All combinations of size 2
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,] "a"  "a"  "a"  "b"  "b"  "c" 
[2,] "b"  "c"  "d"  "c"  "d"  "d" 

[[3]]  # All combinations of size 3
     [,1] [,2] [,3] [,4]
[1,] "a"  "a"  "a"  "b" 
[2,] "b"  "b"  "c"  "c" 
[3,] "c"  "d"  "d"  "d" 

[[4]]  # All combinations of size 4
     [,1]
[1,] "a" 
[2,] "b" 
[3,] "c" 
[4,] "d" 

0
投票

如果您正在寻找dim的所有组合,您可以查看combn包中的combinat功能:

combinat::combn(letters[1:4], 1, simplify = F)

    [[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

[[4]]
[1] "d"

combinat::combn(letters[1:4], 2, simplify = F)
combinat::combn(letters[1:4], 3, simplify = F)
combinat::combn(letters[1:4], 4, simplify = F)

0
投票

在基地R我会使用for循环,sapplylapply

for

for (i in seq_along(dim)) {
  print(dim[-i])
}

[1] "b" "c" "d"
[1] "a" "c" "d"
[1] "a" "b" "d"
[1] "a" "b" "c"

sapply

t( sapply(seq_along(dim), function(i) dim[-i]) )

     [,1] [,2] [,3]
[1,] "b"  "c"  "d" 
[2,] "a"  "c"  "d" 
[3,] "a"  "b"  "d" 
[4,] "a"  "b"  "c" 

lapply

lapply(seq_along(dim), function(i) dim[-i])

[[1]]
[1] "b" "c" "d"

[[2]]
[1] "a" "c" "d"

[[3]]
[1] "a" "b" "d"

[[4]]
[1] "a" "b" "c"

上一篇:UDP客户端仅在特定情况下卡在recvfrom中

下一篇:如何在Knowage中修复空的仪表板屏幕?

相关文章