Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the word separator character in a vector?

Tags:

r

I have a character vector consisting of the following style:

mylist <- c('John Myer Stewert','Steve',' Michael Boris',' Daniel and Frieds','Michael-Myer')

I'm trying to create a character vector like this:

mylist <- c('John+Myer+Stewert','Steve',' Michael+Boris',' Daniel+and+Frieds','Michael+Myer')

I have tried:

test <- cat(paste(shQuote(mylist , type="cmd"), collapse="+"))

That seems wrong. How can I change the word separator in mylist as shown above?

like image 970
Mamba Avatar asked Dec 10 '22 16:12

Mamba


1 Answers

You could use chartr(). Just re-use the + sign for both space and - characters.

chartr(" -", "++", trimws(mylist))
# [1] "John+Myer+Stewert" "Steve"             "Michael+Boris"    
# [4] "Daniel+and+Frieds" "Michael+Myer"  

Note that I also trimmed the leading whitespace since there is really no need to keep it.

like image 88
Rich Scriven Avatar answered Jan 05 '23 08:01

Rich Scriven