user2543622
user2543622

Reputation: 6756

r finding 2nd minimum in row of a data frame and getting column index

I have code as below. It finds the minimum value in a row and column name where that minimum value is. How can i modify my code to get values of 2nd, 3rd, 4th, 5th minimums and respective column names?

x = t( data.frame(c(11,12,1,14,15)) )
colnames(x)=c('a','b','c','d','e')
minimum = apply(x, 1, min)
minimum
index = colnames(x)[apply(x, 1, which.min)]
index

-------------------------------update1

I tried below code. myans_a has 5 columns. But the code fails

#function to find second minimum and associated class name
min <- function(x,n) {
  value = sort(x, FALSE)[n]
  column_name = colnames(x)[which(x == value, arr.ind = TRUE)[2]]
  paste0("Column:",column_name," , Value:",value)
}


myans_a=myans[,c(1:5)]
min(myans_a,3)


> min(myans_a,3)
 Show Traceback

 Rerun with Debug
 Error in `[.data.frame`(x, order(x, na.last = na.last, decreasing = decreasing)) : 
  undefined columns selected 

Upvotes: 0

Views: 5155

Answers (3)

user2543622
user2543622

Reputation: 6756

as commented by akrun below works. Below code will give 2nd minimum...

minimum2=apply(dataframe_name, 1, function(x) (sort(x))[2])
index2=apply(dataframe_name, 1, function(x) names(sort(x)[2]))

Upvotes: 1

G.Arima
G.Arima

Reputation: 1171

You can use the below function
Here n is number of nth minimum value

Step1: Picking the nth value. Since the data is sorted in ascending order therefore, nth minimum value.
Step2: Compare all the values with the nth minimum value and pick the corresponding column of the nth minimum value
arr.value = 'TRUE' shows the value of row number and column number where the condition is true.

x = t( data.frame(c(11,12,1,14,15)) )
colnames(x)=c('a','b','c','d','e')  

min <- function(x,n) {
       value = sort(x, FALSE)[n]
       column_name = colnames(x)[which(x == value, arr.ind = TRUE)[2]]
       paste0("Column:",column_name," , Value:",value)
}


min(x,1) # first minimum value and corresponding column name 
min(x,2) # second minimum value and corresponding column name
....  

Output:
enter image description here Let me know in case of any queries.

Upvotes: 1

989
989

Reputation: 12937

Just this:

colnames(x)[apply(x, 1, order)]
#[1] "c" "a" "b" "d" "e"

Upvotes: 1

Related Questions