val
val

Reputation: 1699

using map() in R purrr

I'm learning to use the map() family of functions in purrr and don't understand why the following works...

df <- data.frame(col1 = c(5,4,3), col2=c("a", "b", "c"))

my_f <- function(v1){
      output <- v1 + 1
      return(output)
    }

addone_v <- df$col1 %>%
  map_dbl(my_f)

but not if change map_dbl() to map(). In the latter case I get the error:

Error in paste("(^", regions, ")", sep = "", collapse = "|") : 
  cannot coerce type 'closure' to vector of type 'character'

which is an error message I don't understand.

I thought map() was the safest to use when I'm uncertain of the type of output I might get.

Upvotes: 1

Views: 1255

Answers (1)

akrun
akrun

Reputation: 886938

If we are updating the same column, apply the function within mutate

library(dplyr)
library(purrr)
df %>%
      mutate(col1 = map_dbl(col1, my_f))

NOTE: Here, it may not require any loop (map) though


If we are applying the function on map, the default output is a list

df$col1 %>% 
   map(my_f)
#[[1]]
#[1] 6

#[[2]]
#[1] 5

#[[3]]
#[1] 4

Upvotes: 1

Related Questions