Home > Software design >  Mutate a new field showing whether or not the row has any NA values using native pipe placeholder
Mutate a new field showing whether or not the row has any NA values using native pipe placeholder

Time:11-13

I would like to mutate a new field with a bool value if the row contains NA or not.

mydf <- data.frame(
  x = 1:5,
  y = 5:1
)

mydf[4,2] <- NA
mydf[3,1] <- NA

I now have a data frame that looks like this:

mydf
   x  y
1  1  5
2  2  4
3 NA  3
4  4 NA
5  5  1

I tried adding a new column to indicate if the row contains NA values:

mydf |> mutate(has_na = complete.cases(_))
Error in mutate(mydf, has_na = complete.cases("_")) : 
  invalid use of pipe placeholder

How can I add a new column within a pipe chain that indicates whether or not the row contains an NA value?

CodePudding user response:

Using across you could do:

library(dplyr)

mydf |> 
  mutate(has_na = complete.cases(across()))
#>    x  y has_na
#> 1  1  5   TRUE
#> 2  2  4   TRUE
#> 3 NA  3  FALSE
#> 4  4 NA  FALSE
#> 5  5  1   TRUE

CodePudding user response:

Using the native pipe, you could also define your own "place-holder":

library(tidyverse)

mydf |>
  (\(d) mutate(d, has_na = complete.cases(d)))()
#>    x  y has_na
#> 1  1  5   TRUE
#> 2  2  4   TRUE
#> 3 NA  3  FALSE
#> 4  4 NA  FALSE
#> 5  5  1   TRUE
  • Related