R 获取按行排列的第一个和第二个最大名称
我试图通过相应的变量名获取行的第一个最大值和第二个最大值。请帮助我实现这一目标 数据帧:R 获取按行排列的第一个和第二个最大名称,r,R,我试图通过相应的变量名获取行的第一个最大值和第二个最大值。请帮助我实现这一目标 数据帧: df1 <- data.frame(AC=c(1.463437e-04,1.023486e-04,1.584040e-05 ), BAT = c(6.555388e-05,5.471379e-01,6.025364e-06), REC = c(6.541157e-05,9.590567e-05,1.581244e-01))
df1 <- data.frame(AC=c(1.463437e-04,1.023486e-04,1.584040e-05 ),
BAT = c(6.555388e-05,5.471379e-01,6.025364e-06),
REC = c(6.541157e-05,9.590567e-05,1.581244e-01))
您可以使用
order
函数获取值的顺序,并从列名中获取相应的名称(colnames
)
要迭代行,请使用apply(df1,1,function)
我把这些都写进了一行:
(df1 <- setNames(cbind(df1, t( # cbind to add the two result columns
apply(df1, 1, function(x) { # apply to iterate over the rows of the data.frame
colnames(df1)[order(x, decreasing = T)][1:2] # get the column names into the decreasing order of their values and select only the first two columns
})
)), c(colnames(df1), "First_Max", "Second_Max"))) # add the correct names for the two extra columns
这里有一个选项,使用
max.col
查找每行最大值的列索引('j1'),将最大值替换为-Inf
,然后再次获取索引('j2'),以创建列
j1 <- max.col(df1, 'first')
j2 <- max.col(replace(df1, cbind(seq_len(nrow(df1)), j1), -Inf), 'first')
transform(df1, First_Max = names(df1)[j1], Second_Max = names(df1)[j2])
# AC BAT REC First_Max Second_Max
#1 0.0001463437 6.555388e-05 6.541157e-05 AC BAT
#2 0.0001023486 5.471379e-01 9.590567e-05 BAT AC
#3 0.0000158404 6.025364e-06 1.581244e-01 REC AC
j1
AC BAT REC First_Max Second_Max
1 0.0001463437 6.555388e-05 6.541157e-05 AC BAT
2 0.0001023486 5.471379e-01 9.590567e-05 BAT AC
3 0.0000158404 6.025364e-06 1.581244e-01 REC AC
j1 <- max.col(df1, 'first')
j2 <- max.col(replace(df1, cbind(seq_len(nrow(df1)), j1), -Inf), 'first')
transform(df1, First_Max = names(df1)[j1], Second_Max = names(df1)[j2])
# AC BAT REC First_Max Second_Max
#1 0.0001463437 6.555388e-05 6.541157e-05 AC BAT
#2 0.0001023486 5.471379e-01 9.590567e-05 BAT AC
#3 0.0000158404 6.025364e-06 1.581244e-01 REC AC