To get all possible K length substrings of a string in R, you can use substring operations and nested loops to iterate through each possible substring.
In this example,
str
with a value of "Hello World"
.substrings
to store all substrings of length 3.substrings
vector.substrings
vector.str <- 'Hello World'
k <- 3
substrings <- character()
for (i in 1:(nchar(str) - k + 1)) {
for (j in i:(i + k - 1)) {
substrings <- c(substrings, substr(str, i, j))
}
}
print(paste('All substrings of length', k, ':', substrings, collapse = ', '))
[1] "All substrings of length 3 : Hel, ell, llo, lo , o W, Wo, Wor, orl, rld"
In this tutorial, we learned How to get all the possible K length Substrings in a String in R language with well detailed examples.