Home > OS >  How to pre-pend and append a backslash for a vector in R
How to pre-pend and append a backslash for a vector in R

Time:08-31

ids <- c("C1322", "C92348", "d2848", "19348")

I would like to prepend and append each element in ids so that the new string looks like the following:

\'C1322\', \'C92348\', \'d2848\', \'19348\'

I tried the following:

> paste0("\'", ids, "\'", collapse = ", ")
[1] "'C1322', 'C92348', 'd2848', '19348'"

But the backslash is not showing up.

CodePudding user response:

You can use cat with paste0 like this:

ids <- c("C1322", "C92348", "d2848", "19348")
cat(paste0("\\'", ids, "\\'", collapse = ", "))
#> \'C1322\', \'C92348\', \'d2848\', \'19348\'

Created on 2022-08-29 with reprex v2.0.2

  • Related