Keep rows separate with write.table R

1.7k Views Asked by At

I'm trying to produce some files that have slightly unusual field seperators.

require(data.table)

dset <- data.table(MPAN = c(rep("AAAA",1000),rep("BBBB",1000),rep("CCCC",1000)),
                   INT01 = runif(3000,0,1), INT02 = runif(3000,0,1), INT03 = runif(3000,0,1))

write.table(dset,"C:/testing_write_table.csv",
            sep = "|",row.names = FALSE, col.names = FALSE, na = "", quote = FALSE, eol = "")

I'm findiong however that the rows are not being kept seperate in the output file, e.g.

AAAA|0.238683722680435|0.782154920976609|0.0570344978477806AAAA|0.9250325632......

Would you know how to ensure the text file retains distinct rows?

Cheers

2

There are 2 best solutions below

2
On BEST ANSWER

Turns out this was a UNIX - Windows encoding issue. So something of a red herring, but perhaps worth recording in case anyone else has this at first perplexing issue.

It turns out that Windows notepad sometimes struggles to render files generated in UNIX properly, a quick test to see if this is the issue is to open in Windows WordPad instead and you may find that it will render properly.

5
On

You are using the wrong eol argument. The end of line argument needs to be a break line:

This worked for me:

require(data.table)

dset <- data.table(MPAN = c(rep("AAAA",1000),rep("BBBB",1000),rep("CCCC",1000)),
                   INT01 = runif(3000,0,1), INT02 = runif(3000,0,1), INT03 = runif(3000,0,1))

write.table(dset,"C:/testing_write_table.csv",  #save as .txt if you want to open it with notepad as well as excel
            sep = "|",row.names = FALSE, col.names = FALSE, na = "", quote = FALSE, eol = "\n")

Using the break line symbol '\n' as the end of line argument creates separate lines for me.