在 R 中使用 NULL 列表列

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))

现在,我想 运行 为每种汽车制造以下功能:

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)

但是,由于

,NULL 列拒绝计算
Error: no applicable method for 'filter_' applied to an object of class "NULL"

我也尝试过使用安全可行的方法,但仍然收到错误消息:

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

有什么好的解决办法吗?

问题是 NULL 被传递到函数 fun_mt() 中。你想用 possibly() 捕捉这个。但是 possibly() 是一个函数运算符,即你传递给它一个函数,它 returns 一个函数。所以,你的电话应该是

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

但这还不适用于 unnest()。而不是字符 "NA"(无论如何都是一个坏主意,而是使用适当的 NA),您必须默认为数据框:

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