0

I'm sure there is a simple explanation for this, but the brain fog is strong this morning and I'm at a loss. I am trying to use purrr::map() to call a function that sometimes returns an NA, but I keep getting an error message:

"Error: Can't convert a logical vector to function"

Here's a simplified case that returns the error:

library(tidyverse)

test <- function(x){
  return(NA)
}

a <- map(.x = 1:2,.f = test())

R classifies NA as a logical variable, but I don't understand why map() is trying to convert this variable to a function when I return it. What am I doing wrong here?

2
  • 4
    I think you want .f = test?
    – aosmith
    Jul 1, 2021 at 15:55
  • 1
    test() is a call because you included the parameter delimiters. If you just used its name, test you might have succeeded. (Once the call got evaluated it returned a logical vector.) The answer to your anthropomorphic question in the title is "because it needed or wanted a function".
    – IRTFM
    Jul 1, 2021 at 16:32

1 Answer 1

2

You need to use

a <- map(.x = 1:2,.f = test)

without the parenthesis. The .f argument needs to be a function -- you do not want to call your function there.

Note that class(test) is "function" but class(test()) is not -- it's "logical" in this case. Leave the parenthesis off when referring to the function itself. Otherwise what you've typed is the same as

# these are the same
a <- map(.x = 1:2, .f = test())
a <- map(.x = 1:2, .f = NA)
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.