wrapping string values in vector with quotes and comma separator

I have a dataframe where the second column is a series of string descriptors that are separated with white space.

col.x          col.y 
company1       science data tech food social 
company2       social tech industry data 

Is there an easy way wrap each string value in the second column in quotes and separate with a comma to look like this?

col.x          col.y 
company1       "science", "data", "tech", "food", "social" 
company2       "social", "tech", "industry", "data" 

>Solution :

We could use gsub to insert the quotes and comma – capture the word ((\\w+)) as a group, in the replacement, wrap the backreference (\\1) of the captured group with double quotes followed by a comma, and then wrap the whole expression with trimws to remove the lagging , at the end of the string

df1$col.y <- trimws(gsub('(\\w+)', '"\\1",', df1$col.y), whitespace = ",")


> df1
     col.x                                       col.y
1 company1 "science", "data", "tech", "food", "social"
2 company2        "social", "tech", "industry", "data"


df1 <- structure(list(col.x = c("company1", "company2"), 
col.y = c("science data tech food social", 
"social tech industry data")), class = "data.frame", row.names = c(NA, 

Leave a Reply