简体   繁体   中英

Keep rows separate with write.table R

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, eg

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

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

Cheers

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM