Splitting a string into fixed-size chunks

Viewed 444

This seems like a really simple task, but I can't find a good solution in base R. I have a character string with 2N characters. How do I split this into a character vector of length N, with each element being a 2-character string?

I could use something like substr with Vectorize:

vss <- Vectorize(substr, c("start", "stop"))
ch <- paste(rep("a", 1e6), collapse="")
vss(ch, seq(1, nchar(ch), by=2), seq(2, nchar(ch), by=2))

but this is really slow for long strings (O(N^2) I believe).

1 Answers
Related