I\'m wondering how I can compare 1 element of a vector with all elements in the other vector. As an example: suppose
x <- c(1:10)
y <- c(10,11,12,13,
Do you mean something like this?
x <- 1:10
y <- c(10,7,11,12,13,14,15,16,17,18)
res <- outer(x, y, `==`)
colnames(res) <- paste0("y=", y)
rownames(res) <- paste0("x=", x)
Which gives you the following matrix:
y=10 y=7 y=11 y=12 y=13 y=14 y=15 y=16 y=17 y=18
x=1 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x=2 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x=3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x=4 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x=5 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x=6 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x=7 FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x=8 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x=9 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x=10 TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
If you want the dimnames to be as y[1]
use
colnames(res) <- paste0("y[", seq_along(y), "]")
rownames(res) <- paste0("x[", seq_along(x), "]")
which gives you:
y[1] y[2] y[3] y[4] y[5] y[6] y[7] y[8] y[9] y[10]
x[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[2] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[3] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[4] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[5] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[6] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[7] FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[8] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[9] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[10] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
To get the index use which
as follows:
which(res)
[1] 10 17
As R
saves matrices rowwise this results in 10 and 17.
If you want the index in x and y component use:
which(res, arr.ind = TRUE)
row col
x=10 10 1
x=7 7 2