-2

I have some char and factor variables in my data frame that look like "A ,A " "B ,B ,B ,B " "C ,C "

I am trying to export the whole data frame to a .csv but the output is very erratic. It makes me even more confused because I want European csv format. When I open the csv file, additional columns are being created based on the commas of that variable.

I have tried the following, nothing worked:

write.table(mydata, "C:/Data/test.csv",row.names=FALSE,sep=";",dec=',')
write.table(mydata,"C:/Data/test.csv",row.names=F, quote = TRUE)
write.table(mydata, "C:/Data/test.csv",row.names=FALSE,sep="\t",dec=',')

#This works well, but I would rather have a .csv than an excel file: 
write.table(mydata, "C:/Data/test.xls",row.names=FALSE,sep="\t",dec=',')

The expected output is a column where the cells don't split, like so:

VariablesWithCommas
A ,A 
B ,B ,B ,B 
C ,C 

Any help is appreciated

Yiyo
  • 103
  • 2
  • 11
  • http://stackoverflow.com/questions/4617935/is-there-a-way-to-include-commas-in-csv-columns-without-breaking-the-formatting – amrrs Sep 01 '16 at 09:55
  • Try `write.csv2` for European csv format. Could you show what you expect as output? – rar Sep 01 '16 at 09:57
  • I suggest a name *.txt for the CSV-file; so Excel (or other SpreadSheet program) will not apply standard options for importing CSV-files. BTW: You didn't include data and didn't specified the desired behavior (and/or expected output) in your question. Please read [ask] and [mcve] – jogo Sep 01 '16 at 09:58
  • 1
    It is really not a good idea to generate a comma separated value file when the value actually can have a comma :-) Maybe your program can not handle the `quote=TRUE` argument correctly? Or what are you doing with the created CSV file? – drmariod Sep 01 '16 at 12:06

1 Answers1

1

I agree with @drmariod that this is not the best idea to create a csv file where separator is a comma - it will just cause too much confusion.

But if you have to then depending on the use you can d a few things,

df <-  data.frame(A = rbind("A ,A",
                  "B ,B ,B ,B ",
                  "C ,C "))

If you want to use this data in R again then:

# write an object  
dput(df, "out")
# read an object
dget("out")

If you want to write to a file then you can use write or writeLines to 'build' your file from lines. Here is one idea:

lines <-   lapply( data.frame(split(df, 1:nrow(df))) ,as.character)

# write rows to file
for(i in 1:nrow(df)){
  write( paste0(lines[i]),  file = "out.txt", append = T)  
}

And to read it back in:

df_2 <- read.csv("out.csv", sep="\n")
USER_1
  • 2,409
  • 1
  • 28
  • 28