String manipulation in R

r, string

Solution

Look at `?gsub` and `?paste`

> paste0("-", gsub("\\.", "-", c("abc.dat", "xyz.dat")))
[1] "-abc-dat" "-xyz-dat"

Notice that I escaped the dot with 2 backslashes. Alternatively, you can use `fixed=TRUE` like this `gsub(".", "-", c("abc.dat", "xyz.dat"), fixed=TRUE)`

If you want a single string, maybe you want to make use of the `collapse` argument to `paste`

> paste(paste0("-", gsub("\\.", "-", c("abc.dat", "xyz.dat"))), collapse=" ")
[1] "-abc-dat -xyz-dat"

Problem

I have a vector of strings: ``` x<-c("abc.dat", "xyz.dat") ``` First I would like to replace the period character "." within each string with another character i.e. "-" minus sign and then append again with "-" minus sign character at the start of each string and finally concatenate all the string within the vector to form a final single string and assigning it to some object like str_final so. ``` >str_final (enter) -abc-dat -xyz-dat ``` Any help will be really appreciated.

Original source