我有一个在Windows上创建文本文件的R脚本。
我使用write.table
和write
函数写入文件。
然后我需要在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 = "")
结果,如NotePad ++所示:
答案 0 :(得分:12)
如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)
答案 1 :(得分:2)
unix类型行结尾可以通过在文件连接中使用wb
写入|二进制模式来实现。
Rnews文章的这句话可能会有所帮助: Ripley, B. D. (2001) Connections. R News, 1/1, 16–7.
文本与二进制文本模式和二进制模式连接之间存在区别。目的是基于文本的功能,如扫描 和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