是否有 purrr-shortcut 来处理列表参数而不是它的元素?

Is there a purrr-shortcut to address the list argument and not its elements?

如果我这样做:

library(tidyverse)

d <- tibble(a = 1:7, b = sample(c(1, NA), 7, replace = TRUE))

d %>%
  mutate(isanymissing = pmap_lgl(list(a, b), ~any(is.na(list(.x, .y))))) %>% # would prefer not to use .x, .y or ..1, ..2 etc
  mutate(isanymissing2 = pmap_lgl(list(a, b), ~any(is.na(.)))) # not working because . == .x == ..1

是否有检索完整参数列表的快捷方式?

这是 dplyr::rowwisec_across 的解决方案:

library(tidyverse)

set.seed(123)

d <- tibble(a = 1:7,
            b = sample(c(1, NA), 7, replace = TRUE),
            c = sample(c(1, NA), 7, replace = TRUE))

d %>% 
  rowwise() %>% 
  mutate(isanymissing = any(is.na(c_across())))

#> # A tibble: 7 x 4
#> # Rowwise: 
#>       a     b     c isanymissing
#>   <int> <dbl> <dbl> <lgl>       
#> 1     1     1    NA TRUE        
#> 2     2     1     1 FALSE       
#> 3     3     1     1 FALSE       
#> 4     4    NA    NA TRUE        
#> 5     5     1    NA TRUE        
#> 6     6    NA    NA TRUE        
#> 7     7    NA     1 TRUE

reprex package (v0.3.0)

于 2021-07-27 创建

因为 rowwise 并不是真正有效的替代方法是 rowSums 和数据选择功能,这里我只使用 cur_data() 来获取所有数据,但是任何 across() 没有函数的表达式可以很好地缩小选择范围。

d %>% 
  mutate(isanymissing = as.logical(rowSums(is.na(cur_data()))))

#> # A tibble: 7 x 4
#>       a     b     c isanymissing
#>   <int> <dbl> <dbl> <lgl>       
#> 1     1     1    NA TRUE        
#> 2     2     1     1 FALSE       
#> 3     3     1     1 FALSE       
#> 4     4    NA    NA TRUE        
#> 5     5     1    NA TRUE        
#> 6     6    NA    NA TRUE        
#> 7     7    NA     1 TRUE

reprex package (v0.3.0)

于 2021-07-27 创建

您也可以按照@tmfmnk 的建议使用if_any

library(dplyr)

d %>% mutate(isanymissing = if_any(c(a, b), is.na))
#To consider all the columns just specifying .fns is enough 
#d %>% mutate(isanymissing = if_any(.fns = is.na))

#     a     b isanymissing
#  <int> <dbl> <lgl>       
#1     1     1 FALSE       
#2     2    NA TRUE        
#3     3    NA TRUE        
#4     4     1 FALSE       
#5     5    NA TRUE        
#6     6     1 FALSE       
#7     7    NA TRUE