简体   繁体   中英

readLines killing R in purrr::map

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?

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.

this will work:

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

from `?purrr::map

Usage
map(.x, .f, ...)
... Additional arguments passed on to .f.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM