# How to compare values in two vectors element wise in R

#1

Hello,

Suppose I have two vectors in R->

x<- c(12,34,26,87)

and another vector

y<- c(2,45,43,21,12)

and I want a vector of dim(y) to be returned which would tell how many of the values in vector x are greater than/less than/equal to the individual values in y. How can I do this in R?

In other words, How can I perform this task without for loop->

z<-rep(0,length(y))
for(i in 1:length(y))
{
for(j in 1:length(x))
{
if(x[j]>y[i])
z[i]=z[i]+1
}
}

z
[1] 4 1 1 3 3

Thanks.

#2

hello @mukesh ,

This can be done using the sqldf package in R.
First you need to convert the vectors into data frames and then use:

``````a <- sqldf("select x,count(*) from x join y where x > y group by x")
``````

This should give:

Hope this helps!!

#4

Try:

``````ans <- vapply(x, function(x) x>y, logical(5))
res <- rowSums(ans)
[1] 4 1 1 3 3
``````

The `vapply` loop recursively evaluates the logical test `x>y`. With that output, the function `rowSums` will tabulate the occurrences of `TRUE` values.