7

Given

str1 <- "0 1 1 2 2 3 3 4 0 4"

I want:

str2 <- "0 1\n1 2\n2 3\n3 4\n0 4"

What's the way to do this with stringr?

andandandand
  • 21,946
  • 60
  • 170
  • 271

2 Answers2

6

We can use gsub to capture one or more digits followed a space followed by digits as a group, followed by a space and replace with the backreference of the captured group followed by \n

gsub("(\\d+\\s\\d+)\\s", "\\1\n", str1)
#[1] "0 1\n1 2\n2 3\n3 4\n0 4"
akrun
  • 874,273
  • 37
  • 540
  • 662
1

This one is not particularly elegant, but it uses stringr:

library(stringr)
str1 <- "0 1 1 2 2 3 3 4 0 4"
spaces <- str_locate_all(str1, " ")[[1]]
for (i in seq(2, nrow(spaces), by = 2)) str_sub(str1, spaces[i, , drop = FALSE]) <- "\n"
str1
## [1] "0 1\n1 2\n2 3\n3 4\n0 4"
Stibu
  • 15,166
  • 6
  • 57
  • 71