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?
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With