Search code examples
rcarriage-return

Eliminate Carriage Return from a table in R


Need advise how to get rid of the CR (carriage returns) when reading in as well as writing out a table in R.

For example, when opened my file in Notepad ++ I see "CRLF" in the end of each row:

ID_1 ID_2 age bmi A1 B2 'CRLF'
124 2532 40 33 0.444 0.333 'CRLF'
126 2103 41 38 0.422 0.137 'CRLF'

I wanted to get rid of the CR (LF is okay):

ID_1 ID_2 age bmi A1 B2 'LF'
124 2532 40 33 0.444 0.333 'LF'
126 2103 41 38 0.422 0.137 'LF'

Solution

  • In Windows which appears to be your OS, open the file in "binary" mode to circumvent the usual OS-dependent way of encoding end-of-line.

    mydf <- data.frame(x=1:10, y=rnorm(10) )
    dest <- file("out.csv", open="wb")
    write.table(mydf, file=dest, quote=FALSE, sep=" ", eol="\n")
    close(f)