如何在R for Windows上使用Unix端行编写文件

Ben*_*Ben 17 r

我有一个R脚本,可以在Windows上创建一个文本文件.

我使用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 = "")
Run Code Online (Sandbox Code Playgroud)

结果,如NotePad ++所示:

在此输入图像描述

Hub*_*rtL 13

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述