Remove all individuals in a column that have at least one NA value in variables with repeated measurements

Viewed 23

I'm new in R and I would like to ask for some help.

I have a dataframe with the following structure:

DF <- data.frame(patient = c(1, 1, 2, 2, 3, 3), treatment = c("baseline", "on-treatment", "baseline", "on-treatment", "baseline", "on-treatment"), cholesterol_value = c(300, 100, 255, NA, 270, 150))

Patient 2 has a baseline cholesterol value but does not have an on-treatment cholesterol value.

I would like to find a way to remove all the values corresponding to patient 2 in a for a loop, staying only with the values corresponding to patients 1 and 3.

Can anyone help me?

Thanks!

3 Answers
library(tidyverse)

DF %>%
  group_by(patient) %>%
  filter(!any(is.na(cholesterol_value)))

Using base R

subset(DF, !patient %in% unique(patient[is.na(cholesterol_value)]))

Here is another base R option using ´aveinsubset`

subset(
  DF,
  !ave(is.na(cholesterol_value), patient, FUN = any)
)

which gives

  patient    treatment cholesterol_value
1       1     baseline               300
2       1 on-treatment               100
5       3     baseline               270
6       3 on-treatment               150
Related