首页 > 解决方案 > purrr::map_if 如果条件为 FALSE,如何返回值?

问题描述

我正在运行一个函数purrr::map,如果数据框不包含数字数据(即 na.omit 不返回任何有效行),它将返回错误。我发现了 map_if,但如果 .p 为假,map_if 似乎返回 .x。有没有办法返回NA。这个例子应该解释我需要什么:

library(openair)
library(tidyverse)

# Build test dataset
df1 <- mydata
df2 <- mydata
df2$no2 <- NA_real_
df3 <- mydata
dfx <- tibble(id = c(1, 2, 3), data = list(df1, df2, df3))

# polarPlot function will return error if dataframe does not contain numeric data (i.e., it only contains NAs)
polarPlot(df2, pollutant = "no2")

# Function to test length of dataframe (i.e., if 0 theneverything is NAs)
check_length <- function(x) (x %>% select(ws, wd, "no2") %>% na.omit() %>% nrow()) > 0
check_length(df1)
check_length(df2)

# purrr::map (is there a way for map_if to return NA if length == 0?) 
dfx %>% mutate(mynewvar = map_if(.x = data, check_length, ~ polarPlot(.x, pollutant = "no2")))

换句话说,我想mynewvar[[2]]返回 NA。

标签: rtidyversepurrr

解决方案


@dylanjm 我发布了一个不知道您是否看不到它的代表。正如您所建议的那样,该功能possibly是我所需要的。

possible_polarPlot <- possibly(polarPlot, otherwise = NA)
out <- dfx %>% mutate(mynewvar = map(.x = data, ~ possible_polarPlot(.x, pollutant = "no2")))
out$mynewvar[[2]] # Returns NA as I was looking for.

推荐阅读