Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string using variable offset

Tags:

string

r

I want to get all substrings of size n and and offset o from a string.

For example, given "abcdef" and substrings of size = 3, offset = 1. I want to obtain a set with "abc","bcd", "cde", "def".

In Mathematica, this can be done with Partition or StringPartition.

Is there a similar function in R?

like image 1000
andandandand Avatar asked May 28 '26 22:05

andandandand


1 Answers

You can just write a wrapper (thanks @thelatemail):

subs = function(x, size, offset){
  nc    = nchar(x)
  first = seq(1, nc-size+1L, by=offset)
  last  = first + size -1L
  substring(x, first, last)
}


subs("abcde",3, 1)
[1] "abc" "bcd" "cde"
like image 107
Frank Avatar answered May 31 '26 14:05

Frank