R: For the group, check if for each unique value of one var, there is at least one observation where the value of var is equal to the value of another var

I think I'm in the right direction with this code, but I'm not quite there yet.

I tried to find something useful on Google and SE, but I didn't seem to be able to formulate the question in such a way as to get the answer I'm looking for.

I could write a for-loop for this, comparing for each id and for each unique value for each row, but I am trying to achieve a higher level of R-understanding and therefore want to avoid loops.

id <- c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5)
a <- c(1,1,1,2,2,2,3,3,4,4,4,5,5,5,6)
b <- c(1,2,3,3,3,4,3,4,5,4,4,5,6,7,8)

require(data.table)
dt <- data.table(id, a, b)

dt
dt[,unique(a) %in% b, by=id]
tmp <- dt[,unique(a) %in% b, by=id]
tmp$id[tmp$V1 == FALSE]

2, 3 5 , : " id, , a, , b ".

2 5, 3. , ID 3 4 4 .

, , , , .

+4
2

dt[, all(sapply(unique(a), function(i) any(a == i & b == i))), by = id]

#   id    V1
#1:  1  TRUE
#2:  2 FALSE
#3:  3 FALSE
#4:  4  TRUE
#5:  5 FALSE

,

dt[, check:=all(sapply(unique(a), function(i) any(a == i & b == i))), by = id]
+2

, data.table-esk , , data.table 1.9.6 ( CRAN 19 Sep 2015). data.table on.

1

dt[a == b][dt[, unique(a), by = id], on = .(id, a == V1)][is.na(b), unique(id)]
[1] 2 3 5

dt, a b . a id.

dt[a == b][dt[, unique(a), by = id], on = .(id, a == V1)]
   id a  b
1:  1 1  1
2:  2 2 NA
3:  3 3  3
4:  3 4 NA
5:  4 4  4
6:  4 4  4
7:  4 5  5
8:  5 5 NA
9:  5 6 NA

NA b , . id, NA, , OP .

2

dt[dt[, unique(a), by = id], on = .(id, a == V1, b == V1), unique(id[is.na(x.a)])]
[1] 2 3 5

dt (!) a id, id, a b. ( a == i & b == i konvas '. , id, NA , .

+1

All Articles