In a dataframe, I want to compare column A and column B and extract value in which A >= B?

天涯浪子 提交于 2021-02-08 02:05:49

问题


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


回答1:


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]




回答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


来源:https://stackoverflow.com/questions/55121314/in-a-dataframe-i-want-to-compare-column-a-and-column-b-and-extract-value-in-whi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!