Comparing sets
In R, a vector may contain duplicated elements:
v = "A"
w = c("A", "A")
However, a set contains only one copy of each element. R treats a vector like a set by taking only its distinct elements, so the two vectors above are regarded as the same:
set...
The %in% operator compares a vector with a set.
v = "A"
w = c("A", "A")
w %in% v
# TRUE TRUE
v %in% w
# TRUE
Each element on the left is treated individually and tested for membership in the set associated with the vector on the right (consisting of all its...
To find every vector of the form (x, y) where x is drawn from vector X and y from Y, we use expand.grid:
X = c(1, 1, 2)
Y = c(4, 5)
expand.grid(X, Y)
# Var1 Var2
# 1 1 4
# 2 1 4
# 3 2 4
# 4 1 5
# 5 1 5
# 6 2 5
The result is a data.frame with one...
unique drops duplicates so that each element in the result is unique (only appears once):
x = c(2, 1, 1, 2, 1)
unique(x)
# 2 1
Values are returned in the order they first appeared.
duplicated tags each duplicated element:
duplicated(x)
# FALSE FALSE TRUE TRUE TRUE
anyDuplicated(x) >...
To count how many elements of two sets overlap, one could write a custom function:
xtab_set <- function(A, B){
both <- union(A, B)
inA <- both %in% A
inB <- both %in% B
return(table(inA, inB))
}
A = 1:20
B = 10:30
xtab_set(A, B)
# inB
...