2016-04-29 65 views
12

我有一个在Windows上创建文本文件的R脚本。如何在R上为Windows编写Unix行尾文件

我同时使用write.tablewrite函数来写入文件。

然后我需要在Unix系统上使用这个文件,但该文件具有Windows结尾行字符(^ M)。

是否有可能在Windows上编写具有Unix尾行字符的R文件?

编辑

这里是一个重复的例子:

output.file <- file.path("./test.txt") 

x <- c(1,2,3,4) 
y <- c(5,6,7,8) 
my.df <- data.frame(x, y) 
my.df[] <- lapply(my.df, sprintf, fmt = "%14.7E") 

write("First line", file = output.file) 
write("Second line", file = output.file, append = TRUE) 
write.table(my.df, 
      row.names = FALSE, 
      col.names = FALSE, 
      file = output.file, 
      quote = FALSE, 
      append = TRUE, 
      sep = "") 

而结果,通过记事本++所见:

enter image description here

+0

见'eol'论据'write.table' – Raad

+0

默认EOL参数设置为\ n,所以它应该已经工作。此外,我使用write()和write.table()函数。写入时没有eol参数,我手动添加\ n。使用Unix读取时仍然有^ M – Ben

回答

10

help(write.table)指出:

要在Windows上编写Unix风格的文件,请使用例如二进制连接。 file = file(“filename”,“wb”)。

在您的例子,只是改变第一线开在最后一个"wb"连接和close文件:

output.file <- file("./test.txt", "wb") 

x <- c(1,2,3,4) 
y <- c(5,6,7,8) 
my.df <- data.frame(x, y) 
my.df[] <- lapply(my.df, sprintf, fmt = "%14.7E") 

write("First line", file = output.file) 
write("Second line", file = output.file, append = TRUE) 
write.table(my.df, 
      row.names = FALSE, 
      col.names = FALSE, 
      file = output.file, 
      quote = FALSE, 
      append = TRUE, 
      sep = "") 

close(output.file) 

enter image description here

2

UNIX类型行尾可以用wb写来实现|文件连接中的二进制模式。

这从Rnews文章报价可能会有所帮助: Ripley, B. D. (2001) Connections. R News, 1/1, 16–7.

文本VS二进制有文本模式和二进制模式连接之间的区别。其目的是基于文本的功能,如扫描 和cat应该使用文本模式连接,二进制模式与 readBin和writeBin一起使用。这种区别还不是始终如一 强制执行,主要的根本区别是文件是否以文本或二进制模式打开(在那里很重要) 。现在看起来好像 以二进制模式打开所有文件,并且在R内部管理行 结尾的翻译将导致更少的意外。从文本模式下的连接读取 转换来自Unix (LF),DOS/Windows(CRLF)和Macintosh(CR)格式(以及所有 连接,而不仅仅是文件)的行尾。

# setup file connection 
con <- file(output.file) 

# open connection 
if(!isOpen(con = con, rw = "wb")) { open(con, open = "wb") } 

# write contents 
write(x = paste(colnames(my.df), collapse = "\t"), file = con) 
for(i in 1:nrow(my.df)){ 
    write(paste(my.df[i, ], collapse = "\t"), file = con) 
} 
close(con) # close and destroy a connection 

# verify file contents 
read.table(output.file, header = TRUE, sep = "\t") 
# x y 
# 1 1 5 
# 2 2 6 
# 3 3 7 
# 4 4 8 
相关问题