R: Getting Unix-like linebreak LF writing files with cat()

亡梦爱人 提交于 2019-12-13 13:42:20

问题


I try to write a character vector to a textfile under Windows 7 / R 3.2.2 x64, and I want unix LF - not Windows CRLF:

v <- c("a","b","c")
cat(nl,file="textfile.txt",sep="\n")

writes

> a[CRLF] 
> b[CRLF] 
> c[CRLF]

cat(paste(nl,sep="\n",collapse="\n"),file="t2.txt")

writes

> a[CRLF] 
> b[CRLF] 
> c

I have also tried write.table(eol="\n") - unsuccessfully as it seems to use cat internally.

I have looked for other workarounds; I tried to find sth. in R\src\main\scan.c, locating the relevant code in line 387ff.

Anyone who knows how I can get UNIX-like LF in my output file?


回答1:


Try to open a file connection in "binary" mode (instead of "text" mode) to prevent system-dependent encoding of the end-of-line:

v <- c("a","b","c")
f <- file("textfile.txt", open="wb")
cat(v,file=f,sep="\n")
close(f)



回答2:


based on the answer from @xb

converter <- function(infile){
    print(infile)
    txt <- readLines(infile)
    f <- file(infile, open="wb")
    cat(txt, file=f, sep="\n")
    close(f)
}


来源:https://stackoverflow.com/questions/32906886/r-getting-unix-like-linebreak-lf-writing-files-with-cat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!