Comparing Vectors Values: 1 element with all other

后端 未结 2 876
一向
一向 2021-01-20 05:44

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,         


        
相关标签:
2条回答
  • 2021-01-20 06:37

    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
    
    0 讨论(0)
  • 2021-01-20 06:46

    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?

    0 讨论(0)
提交回复
热议问题