Search code examples
rcsvdataframeseparatorquoting

Writing data frame to semicolon-delimited CSV where column data contains semi-colon?


How do I write to a CSV with the following data intact? I want to write this data to a CSV file with separator as semicolon but the 2nd row is getting shifted because of the semicolon.

I have a data frame with the following data:

             a <- c(1,2,3,4)
             b <- c("hello","hello;world","hey","there")
             c <- c(10,20,30,40)
             df <- data.frame(a,b,c)
             df
             df
               a           b  c
             1 1       hello 10
             2 2 hello;world 20
             3 3         hey 30
             4 4       there 40

Solution

  • Quote the output:

    a<-c(1,2,3,4)
    b<-c("hello","hello;world","hey","there")
    c<-c(10,20,30,40)
    df<-data.frame(a,b,c)
    write.table(df, file="blah.csv",quote=TRUE, sep = ";")
    

    Gives

    "a";"b";"c"
    "1";1;"hello";10
    "2";2;"hello;world";20
    "3";3;"hey";30
    "4";4;"there";40