How to insert characters into strings

I'm trying the format of a string by inserting a - between in each character. This should be simple, but I'm going through stringr functions to no avail.

what I have
RI
R1A
R1B
C1

what I want:
R-1
R-1-A
R-1-B
C-1

I've tried using the strsplit() but I'm not getting the result I want

There is probably a more elegant solution than this.

X <- c('RI','R1A','R1B','C1')
X
#> [1] "RI"  "R1A" "R1B" "C1"
library(stringr)
CHARS <- str_split(X,pattern = "",simplify = TRUE)
CHARS
#>      [,1] [,2] [,3]
#> [1,] "R"  "I"  ""  
#> [2,] "R"  "1"  "A" 
#> [3,] "R"  "1"  "B" 
#> [4,] "C"  "1"  ""
Xnew <- apply(CHARS,1,function(CH) {
  CH <- paste(CH, collapse = "-")
  str_remove(CH,"-$")
  }
  )
Xnew
#> [1] "R-I"   "R-1-A" "R-1-B" "C-1"

Created on 2022-08-27 by the reprex package (v2.0.1)

Here is an alternative solution using base functions.

x  <- c('RI','R1A','R1B','C1')
x = gsub('', '-', x)
x = substr(x, 2, nchar(x)-1) # removes first and last character

image

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.