Вы можете попробовать это:
split_by_n <- function(string, n = 4) {
missing_zeros_number <- (n - nchar(string)) %% n
extended_string_with_zeros <- paste0(
c(numeric(missing_zeros_number), string),
collapse = "")
total_length <- nchar(extended_string_with_zeros)
substring(
extended_string_with_zeros,
seq(1, total_length, n),
seq(n, total_length, n)
)
}
split_by_n("foo")
split_by_n("foobar")
# [1] "0foo"
# [1] "00fo" "obar"
Наконец, использовать для вектора:
lapply(c("foo", "foobar"), split_by_n)
#[[1]]
#[1] "0foo"
#
#[[2]]
#[1] "00fo" "obar"