Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readLines killing R in purrr::map

Tags:

r

purrr

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?

like image 546
Gubby Avatar asked Jan 02 '23 13:01

Gubby


2 Answers

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.

like image 190
Konrad Rudolph Avatar answered Jan 05 '23 03:01

Konrad Rudolph


this will work:

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

from `?purrr::map

Usage
map(.x, .f, ...)
... Additional arguments passed on to .f.
like image 45
Wimpel Avatar answered Jan 05 '23 03:01

Wimpel