R - stringr 每两个间隔数字添加换行符

R - stringr add newline character every two spaced digits

给定

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

我要:

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

使用 stringr 有什么方法可以做到这一点?

我们可以使用 gsub 来捕获一个或多个数字,然后是 space 然后是数字作为一组,然后是 space 并替换为捕获组的反向引用其次是 \n

gsub("(\d+\s\d+)\s", "\1\n", str1)
#[1] "0 1\n1 2\n2 3\n3 4\n0 4"

这个不是特别优雅,但是用了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"