Equivalent to apply () by row in tidyverse?

I want to insert a new column in data.frame whose value is TRUE if there is at least one invalid value in the row and FALSE otherwise.

For this problem applyis an ideal use case:

EDIT - Added Example

tab <- data.frame(a = 1:10, b = c(NA, letters[2:10]), c = c(LETTERS[1:9], NA))

tab$missing <- apply(tab, 1, function(x) any(is.na(x)))

However, I downloaded the strict package and received this error:apply() coerces X to a matrix so is dangerous to use with data frames.Please use lapply() instead.

I know that I can safely ignore this error, however I was wondering if there is a way to encode it using one of the tidyverse packages in a simple way . I tried unsuccessfully with dplyr:

tab %>% 
  rowwise() %>% 
  mutate(missing = any(is.na(.), na.rm = TRUE))
+4
source share
2 answers

, purrr::pmap, :

library(tidyverse)

tab <- data_frame(a = 1:10, 
                  b = c(NA, letters[2:10]), 
                  c = c(LETTERS[1:9], NA))

tab %>% mutate(missing = pmap_lgl(., ~any(is.na(c(...)))))
#> # A tibble: 10 x 4
#>        a     b     c missing
#>    <int> <chr> <chr>   <lgl>
#>  1     1  <NA>     A    TRUE
#>  2     2     b     B   FALSE
#>  3     3     c     C   FALSE
#>  4     4     d     D   FALSE
#>  5     5     e     E   FALSE
#>  6     6     f     F   FALSE
#>  7     7     g     G   FALSE
#>  8     8     h     H   FALSE
#>  9     9     i     I   FALSE
#> 10    10     j  <NA>    TRUE

c , ..., , is.na any. *_lgl pmap .

, , , , , , R. , , .

tab %>% mutate(missing = rowSums(is.na(as.matrix(.))) > 0)

.

+4

:

library(tidyverse)

tab <- data_frame(a = 1:10, 
                  b = c(NA, letters[2:10]), 
                  c = c(LETTERS[1:9], NA))

tab_1 <- tab %>% mutate(missing = ifelse(is.na(b), TRUE, ifelse(is.na(c), TRUE, FALSE)))

> tab_1
    a    b    c missing
1   1 <NA>    A    TRUE
2   2    b    B   FALSE
3   3    c    C   FALSE
4   4    d    D   FALSE
5   5    e    E   FALSE
6   6    f    F   FALSE
7   7    g    G   FALSE
8   8    h    H   FALSE
9   9    i    I   FALSE
10 10    j <NA>    TRUE
+1

Source: https://habr.com/ru/post/1680897/


All Articles