Às 13:44 de 05/02/2025, Duncan Murdoch escreveu:
If I have this object:

   x <- c("abc\ndef", "", "ghi")

and I write it to a file using `writeLines(x, "test.txt")`, my text editor sees a 5 line file:

   1: abc
   2: def
   3:
   4: ghi
   5:

which is what I'd expect:  the last line in the editor is empty.  If I use `readLines("test.txt")` on that file, I get the vector

   c("abc", "def", "", "ghi")

and all of that is fine.

What I'm looking for is simple code that modifies x to the `readLines()` output, without actually writing and reading it.

My first attempt doesn't work:

   unlist(strsplit(x, "\n"))

because it leaves out the blank line 3.  I can fix that with this ugly code:

   lines <- strsplit(x, "\n")
   lines[sapply(lines, length) == 0] <- list("")
   lines <- unlist(lines)

Surely there's a simpler way to do this?  I'd like to use just base functions, no other packages.

Duncan Murdoch

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting- guide.html
and provide commented, minimal, self-contained, reproducible code.
Hello,

Use ?textConnection.
The 5th line is left out, just like in your code.


x <- c("abc\ndef", "", "ghi")
x |> textConnection() |> readLines()
# [1] "abc" "def" ""    "ghi"


Hope this helps,

Rui Barradas



--
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença 
de vírus.
www.avg.com

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to