melanie chetry
melanie chetry

Reputation: 123

Finding two highest value in a row and then values in the same column but different row

I have a data frame and the problem is I want to find two highest value in a row and then compare those values to what another row has in those columns.


rows <- c("a","b","c","d","e","f","g","h","i")
x1 <- c(1,4,5,7,5,8,9,0,5)
x2 <- c(3,3,5,6,7,8,9,0,7)
x3 <- c(3,1,4,6,7,8,9,5,2)


df <- data.frame(x1=x1,x2=x2, x3=x3, row.names = rows)

Here I get the two highest values from row "a"

sort(df["a",], decreasing = TRUE)[1:2]

Then I would want to find values in row "e" that belongs to these columns where "a" have the top 2 values (and in the same order).

Upvotes: 0

Views: 49

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269441

1) order applied to row a gives the vector which when used as an index to its argument will give it in sorted order so apply that to row e and take the last 2 elements.

o <- order( df["a", ] )
tail(unlist( df["e", o] ), 2)
## x2 x3 
##  7  7 

2) Another possibility if s is the result shown in the question is to index df by its names.

s <- sort(df["a",], decreasing = TRUE)[1:2]
df["e", names(s)]
## x2 x3 
##  7  7 

Upvotes: 2

slyzer
slyzer

Reputation: 19

I am not familiar with r but from an theoretical aspect you need an algorithm, that swaps the whole column based on the two highest values of a.

After that the values in the other rows, you want to compare to, will always be on column 1 and 2.

Upvotes: 0

Related Questions