Purrr::map_df() 删除 NULL 行 [英] Purrr::map_df() drops NULL rows

查看:43
本文介绍了Purrr::map_df() 删除 NULL 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When using purrr::map_df(), I will occasionally pass in a list of data frames where some items are NULL. When I do, map_df() returns a data frame with fewer rows than the the original list.

我假设发生了什么是 map_df() 调用 dplyr::bind_rows() 忽略 NULL 值.但是,我不确定如何识别有问题的行.

I assume what's going on is that map_df() calls dplyr::bind_rows() which ignores NULL values. However, I'm not sure how to identify my problematic rows.

这是一个例子:

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()possably()),但是并不是我遇到了错误——我只是没有得到想要的结果.

I considered wrapping my location accessor in one of purrr's error handling functions (eg. safely() or possibly()), but it's not that I'm running into errors--I'm just not getting the desired results.

使用 map_df() 处理 NULL 值的最佳方法是什么?

What's the best way to handle NULL values with map_df()?

推荐答案

您可以对任何 map*() 使用 (as-of-present undocumented) .null 参数 函数告诉函数在遇到 NULL 值时要做什么:

You can use the (as-of-present undocumented) .null argument for any of the map*() functions to tell the function what to do when it encounters a 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

这篇关于Purrr::map_df() 删除 NULL 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆