Why is R's purrr::map() trying to convert my output to a function?

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?

Upvotes: 0

Views: 372

Answers (1)

MrFlick
MrFlick

Reputation: 206207

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)

Upvotes: 2

Related Questions