gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:26:03 24 4
gpt4 key购买 nike

使用时 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com