7

How to split string in R in following way ? Look at example, please

example:

c("ex", "xa", "am", "mp", "pl", "le") ?

  • 2
    Maybe also somewhat related http://stackoverflow.com/questions/2247045/chopping-a-string-into-a-vector-of-fixed-width-character-elements – David Arenburg Jun 13 '16 at 20:09

2 Answers2

12
x = "example"
substring(x, first = 1:(nchar(x) - 1), last = 2:nchar(x))
# [1] "ex" "xa" "am" "mp" "pl" "le"

You could, of course, wrap it into a function, maybe omit non-letters (I don't know if the colon was supposed to be part of your string or not), etc.

To do this to a vector of strings, you can use it as an anonymous function with lapply:

lapply(month.name, function(x) substring(x, first = 1:(nchar(x) - 1), last = 2:nchar(x)))
# [[1]]
# [1] "Ja" "an" "nu" "ua" "ar" "ry"
# 
# [[2]]
# [1] "Fe" "eb" "br" "ru" "ua" "ar" "ry"
# 
# [[3]]
# [1] "Ma" "ar" "rc" "ch"
# ...

Or make it into a named function and use it by name. This would make sense if you'll use it somewhat frequently.

str_split_pairs = function(x) {
    substring(x, first = 1:(nchar(x) - 1), last = 2:nchar(x))
}

lapply(month.name, str_split_pairs)
## same result as above
Gregor Thomas
  • 104,719
  • 16
  • 140
  • 257
  • Ok, I have a vector of strings (character). How to get from it vector of such pairs ? –  Jun 13 '16 at 19:57
0

Here's another option (though it's slower than @Gregor's answer):

x=c("example", "stackoverflow", "programming")

lapply(x, function(i) {
  i = unlist(strsplit(i,""))
  paste0(i, lead(i))[-length(i)]
})
[[1]]
[1] "ex" "xa" "am" "mp" "pl" "le"

[[2]]
[1] "st" "ta" "ac" "ck" "ko" "ov" "ve" "er" "rf" "fl" "lo" "ow"

[[3]]
[1] "pr" "ro" "og" "gr" "ra" "am" "mm" "mi" "in" "ng"
eipi10
  • 81,881
  • 20
  • 176
  • 248