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



在给定的字符串向量中,我试图在每个具有某些条件(如下所述)的字符上添加一个断行("n")。下面我传递的字符串

d <- "ABCD CDEFG LM NOPQRSTR";

输出预期:

"ABCDn   //added new break line n at fourth character which contained space
CDEFn   //after the fourth character is C, added a new break line n
-G LMn  //started with hypen(-) continuing with the characters.
NOPQn
-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(ABCDn) reset 
character continues
else then if character <> "" like (character including number or special character) then
add break to next line("n") at 4th character(CDEFn) 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 -
}     
}

我无法返回带有断行的完整字符串(每4个字符添加n)和-(如果它包含如示例预期输出中所示)

我从下面的链接得到了灵感,但不能笑起来。

每个字符串的换行

Thanks in advance

带循环符

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

编辑:

在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  ABCDn
# 2  CDEF  CDEFn
# 3 -G LM -G LMn
# 4  NOPQ  NOPQn
# 5 -RSTR   -RSTR

相关内容

  • 没有找到相关文章

最新更新