使元素NA取决于谓词函数 [英] Make elements NA depending on a predicate function

查看:70
本文介绍了使元素NA取决于谓词函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据谓词轻松地将列表或向量的元素更改为NAs?

How can I easily change elements of a list or vectors to NAs depending on a predicate ?

我需要在单个调用中完成此操作,以便在dplyr::mutate调用等中顺利集成...

I need it to be done in a single call for smooth integration in dplyr::mutate calls etc...

预期输出:

make_na(1:10,`>`,5)
# [1]  1  2  3  4  5 NA NA NA NA NA

my_list <- list(1,"a",NULL,character(0))    
make_na(my_list, is.null)
# [[1]]
# [1] 1
# 
# [[2]]
# [1] "a"
# 
# [[3]]
# [1] NA
# 
# [[4]]
# character(0)

注意:

我回答了我的问题,因为我已经找到了一种解决方案,但我很高兴获得替代解决方案.另外,也许此功能已经存在于base R中或打包在一个显着的库中

受到我在推荐答案

我们可以构建以下功能:

We can build the following function:

make_na <- function(.x,.predicate,...) {
  is.na(.x) <- sapply(.x,.predicate,...)
  .x
}

或者更好地利用purrr的魔力:

Or a bit better to leverage purrr's magic :

make_na <- function(.x,.predicate,...) {
  if (requireNamespace("purrr", quietly = TRUE)) {
    is.na(.x) <- purrr::map_lgl(.x,.predicate,...)
  } else {
    if("formula" %in% class(.predicate))
      stop("Formulas aren't supported unless package 'purrr' is installed") 
    is.na(.x) <- sapply(.x,.predicate,...)
  }
  .x
}

这样,如果库purrr可用,我们将使用purrr::map_lgl,否则将使用sapply.

This way we'll be using purrr::map_lgl if library purrr is available, sapply otherwise.

一些例子:

make_na <- function(.x,.predicate,...) {
  is.na(.x) <- purrr::map_lgl(.x,.predicate,...)
  .x
}

一些用例:

make_na(1:10,`>`,5)
# [1]  1  2  3  4  5 NA NA NA NA NA

my_list <- list(1,"a",NULL,character(0))
make_na(my_list, is.null)
# [[1]]
# [1] 1
# 
# [[2]]
# [1] "a"
# 
# [[3]]
# [1] NA
# 
# [[4]]
# character(0)

make_na(my_list, function(x) length(x)==0)
# [[1]]
# [1] 1
# 
# [[2]]
# [1] "a"
# 
# [[3]]
# [1] NA
# 
# [[4]]
# [1] NA

如果安装了purrr,我们可以使用以下简短格式:

If purrr is installed we can use this short form:

make_na(my_list, ~length(.x)==0)

这篇关于使元素NA取决于谓词函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆