I am looking for an efficient way to find the same elements with the same index in two vectors and count them. Say I have two vectors and I want to know how many times I had the realization [1,1] So if I have two vectors (in practice they will be very large), for instance
x=c(2,1,8,1,4)
y=c(9,1,8,0,4)
I want to count that 1 appeared only once in the same position of x and y. I would be very grateful for your help!
We can create a matrix
by cbind
ing the vectors, check whether it is equal to 1, get the rowSums
, if both the vectors have 1 at the same position, it will be 2 and if there are only one 1, the value will be 1. So, convert it to a logical vector
( ==2
or ==1
) and get the count with sum
sum(rowSums(cbind(x, y)==1)==2)
sum(rowSums(cbind(x, y)==1)==1)
Note that this also checks whether the 1 is in either 'x' or 'y' and not only in 'x'
Or with Reduce
sum(Reduce(`&`, lapply(list(x, y), `==`, 1)))
Note that these solutions can be extended to multiple vector
s instead of just two
For all of those looking for that quick tidyverse
fix that you so desperately need:
library(purrr)
map(list(x, y), ~.== 1) %>% reduce(., `&`) %>% sum
For the indices:
map(list(x, y), ~.== 1) %>% reduce(., `&`) %>% which
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.