Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - stringr add newline character every two spaced digits

Tags:

r

stringr

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?

like image 563
andandandand Avatar asked Feb 10 '18 17:02

andandandand


2 Answers

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"
like image 169
akrun Avatar answered Oct 12 '22 15:10

akrun


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"
like image 24
Stibu Avatar answered Oct 12 '22 14:10

Stibu