Comparing Vectors Values: 1 element with all other

2019-02-27 05:51发布

问题:

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,14,1,7) 

Now I can compare the elements parewise

x == y
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

But I want to compare all elements of y with a specific element of x, something like

x[7] == y
[1] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

Is this possible?

回答1:

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


回答2:

If you want to compare each element of x to y, usually one of the 'apply' functions will help.

As follows:

x <- c(1:10)

y <- c(10,11,12,13,14,1,7)

sapply(x,function(z){z==y})

Column i in the output is result from x[i]==y.

Is this what you're looking for?



标签: r vector compare