R find count of values in vector x which are greater than values in vector y

Viewed 201

Suppose there are two vectors

x = c(20,30,50) 

and

y = c(25,40,60).

Objective is to find the number's in x which are greater than numbers in y .

So here it will be 2 as 30 > 25 and 50 > 40

2 Answers

We can use outer to do comparison of each element of 'x' with that of 'y', get the colSums and get the count of numbers that are greater than 0 with sum

sum(colSums(outer(x, y, `>`)) > 0)

One way to do this is to define a dataframe with the vectors

y <- data.frame(y=c(25,40,60,11))
x <- data.frame(x=c(20,30,50,12))

Then you can do an easy comparison and retrieval as shown below

> y[y<x]
[1] 11

> y[y>x]
[1] 25 40 60
Related