gpt4 book ai didi

r - 将 df$col 分成三组,在 r 中使用尽可能多的组合

转载 作者:行者123 更新时间:2023-12-04 09:37:13 26 4
gpt4 key购买 nike

假设,我有一个长度为 8 的 df$col:

1
2
3
4
5
6
7
8

我想把这个 col 分成三个不同的部分,尽可能多的“可能性”。像这样:

1  2  345678 

1 23456 78

1 234567 8

123 45 678

123456 7 8

so on...

有人可以在 r 中提出一个简单的解决方案吗?谢谢

最佳答案

我把这个案例概括了一下:

vec <- letters[1:8]    
n <- 2
combn(length(vec)-1,n,function(x){
for(i in rev(x)) vec <- append(vec," ",i)
paste0(vec,collapse="")})
# [1] "a b cdefgh" "a bc defgh" "a bcd efgh" "a bcde fgh" "a bcdef gh" "a bcdefg h" "ab c defgh" "ab cd efgh" "ab cde fgh" "ab cdef gh"
# [11] "ab cdefg h" "abc d efgh" "abc de fgh" "abc def gh" "abc defg h" "abcd e fgh" "abcd ef gh" "abcd efg h" "abcde f gh" "abcde fg h"
# [21] "abcdef g h"

我们的想法是您有 7 个可以切割的位置,因此我们使用 combn 在其中进行采样。它提供了一个很好的矩阵,我们可以通过 combnFUN 参数即时apply 以形成我们的串联字符串。

我最后使用了一个很好的旧 for 循环来概括 n 参数,但我们也可以使用递归函数来做到这一点。

关于r - 将 df$col 分成三组,在 r 中使用尽可能多的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49522657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com