I have a data with three variables. Patient ID as ID, Visit as Visit, and a third variable as Var. I have two visits and I would like to subset the IDs:
ID Visit Var
1 1 2
1 2 2
2 1 1
2 2 2
3 1 2
3 2 1
4 1 2
4 2 NA
You can subset using [
and using ==
for equal, &
for and, is.na
to test for missing values.
unique(x$ID[x$Visit == 2 & is.na(x$Var)])
#[1] 4
intersect(unique(x$ID[!is.na(x$Var) & x$Var == 2 & x$Visit==1])
, unique(x$ID[!is.na(x$Var) & x$Var == 1 & x$Visit==2]))
#[1] 3
Data:
x <- read.table(header=TRUE, text="ID Visit Var
1 1 2
1 2 2
2 1 1
2 2 2
3 1 2
3 2 1
4 1 2
4 2 NA")