Reputation: 6756
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
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
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
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:
Let me know in case of any queries.
Upvotes: 1