r - Purrr::map_df() 删除 NULL 行

标签 r tidyverse purrr

使用时 purrr::map_df() ,我偶尔会传入一个数据框列表,其中有些项目是 NULL .当我这样做时,map_df()返回行数少于原始列表的数据框。

我假设正在发生的事情是 map_df()电话dplyr::bind_rows()忽略 NULL值。但是,我不确定如何识别有问题的行。

下面是一个例子:

library(purrr)

problemlist  <- list(NULL, NULL, structure(list(bounds = structure(list(northeast = structure(list(
    lat = 41.49, lng = -71.46), .Names = c("lat", "lng"
), class = "data.frame", row.names = 1L), southwest = structure(list(
    lat = 41.49, lng = -71.46), .Names = c("lat", "lng"
), class = "data.frame", row.names = 1L)), .Names = c("northeast", 
"southwest"), class = "data.frame", row.names = 1L), location = structure(list(
    lat = 41.49, lng = -71.46), .Names = c("lat", "lng"
), class = "data.frame", row.names = 1L), location_type = "ROOFTOP", 
    viewport = structure(list(northeast = structure(list(lat = 41.49, 
        lng = -71.46), .Names = c("lat", "lng"), class = "data.frame", row.names = 1L), 
        southwest = structure(list(lat = 41.49, lng = -71.46), .Names = c("lat", 
        "lng"), class = "data.frame", row.names = 1L)), .Names = c("northeast", 
    "southwest"), class = "data.frame", row.names = 1L)), .Names = c("bounds", 
"location", "location_type", "viewport"), class = "data.frame", row.names = 1L))

# what actually happens
map_df(problemlist, 'location')

#     lat    lng
# 1 41.49 -71.46


# desired result
map_df_with_Null_handling(problemlist, 'location') 

#     lat    lng
# 1    NA     NA
# 2    NA     NA
# 3 41.49 -71.46

我考虑过包装我的 location purrr 的错误处理函数之一(例如 safely()possibly() )中的访问器,但这并不是说我遇到了错误——我只是没有得到想要的结果。

最好的处理方式是什么NULL值与 map_df() ?

最佳答案

您可以使用(截至目前未记录的).null任何 map*() 的参数函数告诉函数在遇到 NULL 时该怎么做值(value):

map_df(problemlist, 'location', .null = data_frame(lat = NA, lng = NA) )

#     lat    lng
# 1    NA     NA
# 2    NA     NA
# 3 41.49 -71.46

关于r - Purrr::map_df() 删除 NULL 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48428107/

相关文章:

R:运行函数,直到函数先前输出的条件测试对于所有行都为 True

r - 单独 tibble 列表列中的矩阵求和

r - 用rvest阅读html。如何检查CSS选择器类是否包含任何内容?

JAGS 中的运行时错误

r - 如何将原始输入转换为 R 中的索引值

r - 将 data.frame 列名称传递给使用 purrr::map 的函数

r - 使用 purrr 递归处理任意层次结构

r - 无效的行类型 : must be length 2, 4、6 或 8

R read_excel 或 readxl 具有多个工作表的多个文件 - 绑定(bind)

r - Tidyverse min{x, 1-x} 按列