John legend2
John legend2

Reputation: 920

find the column with nth lowest value in r

I left a question for finding the column with the lowest value and here is the link find the column with lowest value in r

This perfectly works for me. However, I have a similar but different problem. If I want to find the column with 2nd lowest, 3rd lowest value ,, and nth lowest value. How to do it?

Upvotes: 5

Views: 247

Answers (3)

AdamO
AdamO

Reputation: 4910

A solution which allows for multiple possible columns having the $k$-th lowest value: Use which with arr.ind=T

set.seed(1234)
M = matrix(sample(50, 100, replace=T), ncol=4)

## columns with the 6th lowest value, e.g. 6 (two instances in cols 1 & 4)
which(M == unique(sort(M))[6], arr.ind = T)

Gives:

> which(M == unique(sort(M))[6], arr.ind = T)
     row col
[1,]   1   1
[2,]  20   4

Upvotes: 1

RoyalTS
RoyalTS

Reputation: 10203

A tidyverse solution:

library(dplyr)
library(tidyr)

df <-  as.data.frame(matrix(sample(20,20), ncol = 4))

df %>%
  tidyr::gather(column, value) %>%
  arrange(value) %>%
  filter(row_number() == 2) %>%
  pull(column)

Upvotes: 1

G5W
G5W

Reputation: 37641

Here is an example of getting the column numbers of the three lowest columns in each row.

set.seed(1234)
M = matrix(sample(20,20), ncol=4)
M
     [,1] [,2] [,3] [,4]
[1,]    3   10    7    9
[2,]   12    1    5   17
[3,]   11    4   20   16
[4,]   18    8   15   19
[5,]   14    6    2   13
t(apply(M, 1, function(x) head(order(x),3)))
     [,1] [,2] [,3]
[1,]    1    3    4
[2,]    2    3    1
[3,]    2    1    4
[4,]    2    3    1
[5,]    3    2    4

Upvotes: 5

Related Questions