我有一个从0到9的整数向量,并且需要这些连续向量元素的所有唯一的可能组合,包括原始元素。
> vec <- 0:9
> vec
[1] 0 1 2 3 4 5 6 7 8 9任务类似于this question。主要(和棘手)的区别是,我只需要连续组合(例如"0", "01", "012", ... "0123456789", ... "1", ... "123456789"),而不需要非连续组合(如"013")。
我将如何创建这个组合子集?
发布于 2022-06-30 10:49:07
下面是嵌套的sapply方法
unlist(
sapply(
seq_along(vec),
function(k) {
sapply(
k:length(vec),
function(l) paste0(vec[k:l], collapse = "")
)
}
)
)产
[1] "0" "01" "012" "0123" "01234"
[6] "012345" "0123456" "01234567" "012345678" "0123456789"
[11] "1" "12" "123" "1234" "12345"
[16] "123456" "1234567" "12345678" "123456789" "2"
[21] "23" "234" "2345" "23456" "234567"
[26] "2345678" "23456789" "3" "34" "345"
[31] "3456" "34567" "345678" "3456789" "4"
[36] "45" "456" "4567" "45678" "456789"
[41] "5" "56" "567" "5678" "56789"
[46] "6" "67" "678" "6789" "7"
[51] "78" "789" "8" "89" "9"另一种选择是sapply + embed
unlist(
sapply(
seq_along(vec),
function(k) {
do.call(paste0, rev(data.frame(embed(vec, k))))
}
)
)这给
[1] "0" "1" "2" "3" "4"
[6] "5" "6" "7" "8" "9"
[11] "01" "12" "23" "34" "45"
[16] "56" "67" "78" "89" "012"
[21] "123" "234" "345" "456" "567"
[26] "678" "789" "0123" "1234" "2345"
[31] "3456" "4567" "5678" "6789" "01234"
[36] "12345" "23456" "34567" "45678" "56789"
[41] "012345" "123456" "234567" "345678" "456789"
[46] "0123456" "1234567" "2345678" "3456789" "01234567"
[51] "12345678" "23456789" "012345678" "123456789" "0123456789"发布于 2022-06-30 23:48:30
下面是与RcppAlgos的一条直线(我是作者):
RcppAlgos::comboGeneral(10, 2, repetition = TRUE, FUN = function(r) {
paste((0:9)[r[1]:r[2]], collapse = "")
}, FUN.VALUE = "a")
[1] "0" "01" "012" "0123" "01234" "012345"
[7] "0123456" "01234567" "012345678" "0123456789" "1" "12"
[13] "123" "1234" "12345" "123456" "1234567" "12345678"
[19] "123456789" "2" "23" "234" "2345" "23456"
[25] "234567" "2345678" "23456789" "3" "34" "345"
[31] "3456" "34567" "345678" "3456789" "4" "45"
[37] "456" "4567" "45678" "456789" "5" "56"
[43] "567" "5678" "56789" "6" "67" "678"
[49] "6789" "7" "78" "789" "8" "89"
[55] "9" 发布于 2022-07-01 09:33:43
基于purrr::map的另一种可能的解决方案
library(tidyverse)
map(0:9, \(x) map(x:9, \(y) str_c(x:y, collapse = ""))) %>% unlist
#> [1] "0" "01" "012" "0123" "01234"
#> [6] "012345" "0123456" "01234567" "012345678" "0123456789"
#> [11] "1" "12" "123" "1234" "12345"
#> [16] "123456" "1234567" "12345678" "123456789" "2"
#> [21] "23" "234" "2345" "23456" "234567"
#> [26] "2345678" "23456789" "3" "34" "345"
#> [31] "3456" "34567" "345678" "3456789" "4"
#> [36] "45" "456" "4567" "45678" "456789"
#> [41] "5" "56" "567" "5678" "56789"
#> [46] "6" "67" "678" "6789" "7"
#> [51] "78" "789" "8" "89" "9"https://stackoverflow.com/questions/72814385
复制相似问题