繁体   English   中英

Purrr :: map_df()删除NULL行

[英]Purrr::map_df() drops NULL rows

当使用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的错误处理函数之一中(例如safe safely()possibly() ),但这并不是我遇到错误-我只是没有得到想要的结果。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM