在 R 中的某些条件下,为每 4 个索引在字符串中添加一个新的换行符

add a new break line in a string for every 4 index with some conditions in R

在给定的字符串向量中,我试图在具有某些条件(如下所述)的每个字符处添加一个换行符(“\n”)。我传递的以下字符串

d <- "ABCD CDEFG LM NOPQRSTR";

预期输出:

"ABCD\n   //added new break line \n at fourth character which contained space
 CDEF\n   //after the fourth character is C, added a new break line \n
 -G LM\n  //started with hypen(-) continuing with the characters.
 NOPQ\n
 -RSTR"

条件:

add a new break line i,e "\n" for every 4 characters position if and only based on the below logic
 if the character=""(blank) then
     add break to next line ("\n") at 4th character like above sample output(ABCD\n) reset 
     character continues
else then if character <> "" like (character including number or special character) then
    add break to next line("\n") at 4th character(CDEF\n) along with hypen(-) i,e C in 
    next line 

希望我已尽力解释问题。有不懂的可以自由写。 我试过的代码: 我是 R 世界的新手,这是我尝试过的逻辑。请帮忙

c <- 4  //setting the position index
for (i in 1:nchar(d)){
    //print(substr(d, i,i))
    a<-substr(d, i,c) //get the 4th index
    if(a=""){   //if 4th character is blank
      d<-paste0(a,"\n")  //add a break new line (\n) 
    }else {  
      d<-paste0("-",a)   //if the character contains 4th is a character put that character in 
                           next line continue with -
 }     
}

我无法 return 完整的字符串,其中添加了分隔线(\n 每 4 个字符)和 -(如果它包含示例预期输出中所示)

我得到了下面的灵感link,但无法破解

提前致谢

带循环

d <- "ABCD CDEFG LM NOPQRSTR";
dsp <- strsplit(d, '')[[1L]]
step <- 5L
pos <- 5L
while (pos < length(dsp)) {
  if (dsp[pos] == " ") {
    dsp[[pos]] <- '\n'
  } else {
    dsp <- c(dsp[1L:(pos-1L)], "\n-", dsp[-(1:pos-1L)])
  }
  pos <- pos + step
}

cat(paste(dsp, collapse = ""))
# ABCD
# CDEF
# -G LM
# NOPQ
# -RSTR

编辑:

到return作为data.frame中的一列(二选一):

data.frame(
  x = strsplit(paste(dsp, collapse = ""), split = "\n")[[1]],
  y = strsplit(paste(dsp, collapse = ""), split = "(?<=\n)", perl = TRUE)[[1]]
)

#       x       y
# 1  ABCD  ABCD\n
# 2  CDEF  CDEF\n
# 3 -G LM -G LM\n
# 4  NOPQ  NOPQ\n
# 5 -RSTR   -RSTR