2
Cars         A      B
Honda        5      3     
Kia          7      5
BMW          4      8
Mazda        6      10
Hyundai      15     12
Lexus        22     19
Toyota       40     50
Jeep         60     50

The above figure is my dataframe. From this i want to compare column A with column B and extract values in A which are greater or equals to B (A>=B).

I tried to solve this by using function

pmax(Cars$A,Cars$B)

But it gave me this result - 5,7,8,10,15,22,50,60

The result I want - 5,7,15,22,60

thothal
  • 16,690
  • 3
  • 36
  • 71
Alex
  • 65
  • 5

2 Answers2

5

pmax is the parallel maximun, from ?pmax

Returns the (regular or parallel) maxima and minima of the input values. ‘pmax*()’ and ‘pmin*()’ take one or more vectors as arguments, recycle them to common length and return a single vector giving the ‘parallel’ maxima (or minima) of the argument vectors.

That is, at each position it returns the larger value - that's what you see in your output.

What you want is Cars$A[Cars$A >= Cars$B]

thothal
  • 16,690
  • 3
  • 36
  • 71
2

I'm using a sample data from mtcars

data("mtcars")
newdf <- data.frame(cars = rownames(mtcars)[1:10])
newdf$A <- sample(1:10,replace = T)
newdf$B <- sample(1:10,replace = T)
newdf$out <- ifelse(newdf$A >= newdf$B, newdf$A, newdf$B)

Output:

> head(newdf)
               cars  A B out
1         Mazda RX4  9 9   9
2     Mazda RX4 Wag 10 9  10
3        Datsun 710  6 3   6
4    Hornet 4 Drive  3 6   2
5 Hornet Sportabout  4 5   2
6           Valiant  2 2   9
snair.stack
  • 405
  • 4
  • 13