user3570187
user3570187

Reputation: 1773

concatenate strings of one column separated by comma in R

I would like to concatenate string with double quotes which is in a column followed by comma as I would like import this to an SQL query.

   A<-c('John', 'Kate', 'Kaitlyn', 'Arun',' Chen')
   df<- data.frame(A)
    

So I would like to concatenate all the rows of A and get a string from this column A and would like to get the output as text file. Below is the expected text. Any suggestions?

        "John", "Kate", "Kaitlyn", "Arun", "Chen" 

Upvotes: 1

Views: 1038

Answers (1)

Duck
Duck

Reputation: 39595

Try this approach:

#Data
A<-c('John', 'Kate', 'Kaitlyn', 'Arun',' Chen')
df<- data.frame(A,stringsAsFactors = F)
df$A <- paste0('\"',trimws(df$A),'\"')
#Collapse
df2 <- data.frame(val=paste0(df$A,collapse = ', '),stringsAsFactors = F)
#Export
write.table(df2,file='File.txt',row.names = F,col.names = F,quote = F)

Output:

enter image description here

Upvotes: 1

Related Questions