jrzelling jrzelling - 3 months ago 11
R Question

concatenate a string that contains backquote characters R

I have a string that contains back quotes, which mess up the concatenate function. If you try to concatenate with back ticks, the concatenate function doesn't like this:

a <- c(`table`, `chair`, `desk`)
Error: object 'chair' not found


So I can create the variable:

bad.string <- "`table`, `chair`, `desk`"
a <- gsub("`", "", bad.string)


That gives a string
"table, chair, desk".


It then should be like:

good.object <- c("table", "chair", "couch", "lamp", "stool")


I don't know why the backquotes cause the concatenate function to break, but how can I replace the string to not have the illegal characters?

Answer

Try:

good.string <- trimws(unlist(strsplit(gsub("`", "", bad.string), ",")))

Here gsub() is used to remove the backticks, strsplit converts a single string into a list of strings, where the comma in the original string denotes the separation, unlist() converts the list of strings into a vector of strings and trimws() deletes trailing or leading whitespaces.