Misha
Misha

Reputation: 3126

purrring with NULL listcolumns in R

library(tidyverse)
data(mtcars)
mtcars <- rownames_to_column(mtcars,var = "car")
mtcars$make <- map_chr(mtcars$car,~strsplit(.x," ")[[1]][1])

mt2 <- mtcars %>% select(1:8,make) %>% nest(-make,.key = "l")
mt4<-mt2[1:5,]
mt4[c(1,5),"l"] <- list(list(NULL))

Now, I´d like to run the following function for each make of car:

fun_mt <- function(df){
      a <- df %>%
        filter(cyl<8) %>%
        arrange(mpg) %>% 
        slice(1) %>% 
        select(mpg,disp)
      return(a)  
    } 
mt4 %>% mutate(newdf=map(l,~possibly(fun_mt(.x),otherwise = "NA"))) %>% unnest(newdf)

However, the NULL columns refuse to evaluate due to

Error: no applicable method for 'filter_' applied to an object of class "NULL"

I also tried using the safely and possibly approach, but still I get an error msg:

Error: Don't know how to convert NULL into a function

Any good solutions to this?

Upvotes: 1

Views: 1123

Answers (1)

Maximilian Girlich
Maximilian Girlich

Reputation: 306

The problem is that NULL gets passed into the function fun_mt(). You wanted to catch this with possibly(). But possibly() is a function operator, i.e. you pass it a function and it returns a function. So, your call should have been

~ possibly(fun_mt, otherwise = "NA"))(.x)

But this doesn't yet work with unnest(). Instead of a character "NA" (a bad idea anyway, rather use a proper NA) you would have to default to a data frame:

~ possibly(fun_mt, otherwise = data.frame(mpg = NA, disp = NA))(.x)

Upvotes: 2

Related Questions