Purrr::map_df() 删除 NULL 行 [英] Purrr::map_df() drops NULL rows
问题描述
当使用 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屋!