I have a list of names like below
100m LJ SP HJ 400m
I would like to have this in the following format:
"100m", "LJ", "SP", "HJ", "400m"
Is there any function that preexisted in R?
CodePudding user response:
You could use gsub()
here, twice:
x <- "100m LJ SP HJ 400m"
output <- gsub("\\s ", ", ", gsub("(\\S )", "\"\\1\"", x))
output
[1] "\"100m\", \"LJ\", \"SP\", \"HJ\", \"400m\""
CodePudding user response:
We can use dQuote
library(stringr)
str_replace_all(str1, '\\w ', function(x) dQuote(x, FALSE))
#[1] "\"100m\" \"LJ\" \"SP\" \"HJ\" \"400m\""
Or in base R
paste(dQuote(strsplit(str1, "\\s ")[[1]], FALSE), collapse = " ")
[1] "\"100m\" \"LJ\" \"SP\" \"HJ\" \"400m\""
data
str1 <- "100m LJ SP HJ 400m"