purrr :: map_if如果条件为FALSE,如何返回值?

时间:2019-02-25 20:02:20

标签: r tidyverse purrr

我正在使用purrr::map运行一个函数,如果数据框不包含数字数据(即na.omit不返回任何有效行),该函数将返回错误。我发现了map_if,但如果.p为false,似乎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。

1 个答案:

答案 0 :(得分:0)

@dylanjm我发布了一个reprex,不确定您是否看不到它。正如您所建议的,功能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.