Search code examples
rstringstring-concatenation

Concatenate strings with quotes and commas in r


I got stuck with the following problem.

I have to download a file daily that looks like a matrix. One of the columns is in the format: 9766 JP 6367 JP 9983 JP 3407 JP 8309 JP and so on. The class of the column is factor.

I need to transform this column in this format:

"9766 JP", "6367 JP", "9983 JP", "3407 JP", "8309 JP"

I tried many possible solutions suggested on this website but none seems to work for me.

Thank you


Solution

  • The question is downvoted because it is not clear what your source data looks like, or what it exactly is, what you want to achieve.

    Maybe this example will help

    library(stringr)
    
    s <- "9766 JP 6367 JP 9983 JP 3407 JP 8309 JP"
    
    v <- str_extract_all(s, '[0-9]{4} [A-Z]{2}')[[1]]
    
    r <- paste0(v, collapse='","', sep="")
    
    sq <- paste0("'",paste0(v, sep="", collapse="','"),"'")
    

    results:

    > v
    [1] "9766 JP" "6367 JP" "9983 JP" "3407 JP" "8309 JP"
    > r
    [1] "9766 JP\",\"6367 JP\",\"9983 JP\",\"3407 JP\",\"8309 JP"
    > sq
    [1] "'9766 JP','6367 JP','9983 JP','3407 JP','8309 JP'"