我的代码如下。它在行和列名称中找到最小值的最小值。如何修改我的代码以获取第2,第3,第4,第5最小值和各列名称的值?
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
我试过下面的代码。 myans_a有5列。但是代码失败了
#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
答案 0 :(得分:1)
就是这样:
colnames(x)[apply(x, 1, order)]
#[1] "c" "a" "b" "d" "e"
答案 1 :(得分:1)
您可以使用以下功能
这里 n 是第n个最小值
第1步:选择第n个值。由于数据按升序排序,因此,第n个最小值
Step2:将所有值与第n个最小值进行比较,并选择第n个最小值的相应列
arr.value ='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
....
答案 2 :(得分:1)
由akrun评论下面的作品。下面的代码将给出第二个最小值...
minimum2=apply(dataframe_name, 1, function(x) (sort(x))[2])
index2=apply(dataframe_name, 1, function(x) names(sort(x)[2]))