r - 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。
解决方案
@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.
推荐阅读
- vb.net - 在 VB.NET 中将图标导出为位图图像
- qt - 将异步 QLocalServer 与 QEventLoop 一起使用
- android - android volley 在一个请求中发送和接收
- r - geom_text_repel 标签/引线未对齐某些点,ggplot2
- php - HTML 数据到 PHP
- arrays - numpy 将数据从一个数组复制到另一个数组
- cookies - 如何实施 Odoo 数据隐私通知
- java - 如何将不同类的图形组件添加到 jframe?
- flutter - Flutter 使用子小部件中的控制器
- python - TensorFlow 错误:ValueError("形状 %s 和 %s 不兼容"% (self, other))