Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R for Windows上使用Unix行尾写入文件_R - Fatal编程技术网

如何在R for Windows上使用Unix行尾写入文件

如何在R for Windows上使用Unix行尾写入文件,r,R,我有一个在Windows上创建文本文件的R脚本 我使用write.table和write函数写入文件 然后,我需要在Unix系统上使用此文件,但该文件具有Windows行尾字符(^M) 在具有Unix行尾字符的Windows上,是否可以使用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

我有一个在Windows上创建文本文件的R脚本

我使用
write.table
write
函数写入文件

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

在具有Unix行尾字符的Windows上,是否可以使用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 = "")
output.file如
帮助(write.table)
中所述:

要在Windows上编写Unix样式的文件,请使用二进制连接,例如。 文件=文件(“文件名”、“wb”)

在您的示例中,只需更改第一行以打开
“wb”
连接,并在末尾关闭
文件:

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)

output.fileunix类型的行尾可以通过在文件连接中使用
wb
write |二进制模式来实现

这篇引用自Rnews文章的话可能会有所帮助:

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

#设置文件连接

请参见
write的
eol
参数。默认情况下,table
的eol参数设置为\n,因此它应该已经工作了。此外,我使用write()和write.table()函数。写入中没有eol参数,我手动添加。在使用Unix阅读时仍然获得^M
# 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