Equivalent of apply() by row in the tidyverse?

Viewed 7723

I want to insert a new column into a data.frame, which value is TRUE when there is at least one missing value in the row and FALSE otherwise.

For that problem, apply is a a perfect 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 loaded the strict package, and got 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 was a way to code it using one of the tidyverse packages, in a simple manner. I tried unsuccessfully with dplyr:

tab %>% 
  rowwise() %>% 
  mutate(missing = any(is.na(.), na.rm = TRUE))
3 Answers

You can use the complete.cases function:

tab %>% mutate(missing = !complete.cases(.))

To remove rows with one or more NAs, use:

tab %>% filter(complete.cases(.))
Related