4

I keep losing my session* in the console when trying to perform readLines (from base) with map (from purrr).

*Don't get new line, and R doesn't seem to be running anything

If I input a vector of file paths:

paths <- c("a/file.csv", "a/nother_file.csv")

And try and get all top lines out with map and readLines, R dies.

result <- map(paths, readLines(n = 1))

But if I do:

result <- map(1:2, function(x) readLines(paths[x], n = 1))

It works.

What am I doing wrong?

Gubby
  • 43
  • 3

2 Answers2

6

The solution has already been posted. Here’s a brief explanation what happens in your case:

To use purrr::map, you are supposed to pass it a function. But readLines(n = 1) isn’t a function, it’s a function call expression. This is very different: to give another example, sum is a function, sum(1 : 10) is a function call expression, which evaluates to the integer value 55. But sum, on its own, evaluates to … itself: a function, which can be called (and you can’t call sum(1 : 10): it’s just an integer).

When you write readLine(n = 1), that function is invoked immediately when map is called — not by purrr on the data, but rather just as it stands. The same happens if you invoke readLines(n = 1) directly, without wrapping it in map(…).

But this isn’t killing the R session. Instead, it’s telling readLines to read from the file that is specified as its default. Looking at the documentation of the function, we see:

readLines(con = stdin(), n = -1L, ok = TRUE, warn = TRUE,
          encoding = "unknown", skipNul = FALSE)

con = stdin() — by default, readLines is reading from standard input. In an interactive terminal, this blocks until the standard input (that is, the interactive terminal) sends an “end of file” instruction. On most command lines, you can simulate this by pressing the key combination Ctrl+D. Inside RStudio, the behaviour may be different.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Thanks very much. The difference between a _function_ and a _function call expression_ was what I needed to know. – Gubby Dec 10 '18 at 16:52
3

this will work:

result <- map(paths, readLines, n = 1)

from `?purrr::map

Usage
map(.x, .f, ...)
... Additional arguments passed on to .f.
Wimpel
  • 26,031
  • 1
  • 20
  • 37