Suppose, I have a df$col with length eight:
1
2
3
4
5
6
7
8
I want to divide this col into three different parts with as many "possibilities" as possible. Like this:
1 2 345678
1 23456 78
1 234567 8
123 45 678
123456 7 8
so on...
Can someone suggest a simple solution in r? Thanks
I generalized the case a bit:
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"
The idea is that you have 7 places where it's possible to cut, so we sample among them using combn. It gives a nice matrix that we can apply on on the fly through the FUN argument of combn to form our concatenated strings.
I used a good old for loop in the end to generalize the n parameter but we could do it with a recursive function as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With