鉴于此表
df <- data.frame(col1 = c(letters[3:5], "b","a"),
col2 = c(2:3, 1,1,1))
如何判断R返回&#34; a&#34;。 这意味着,从值为1的三个字符(最低值的平局),我想只按字母顺序选择第一个
答案 0 :(得分:0)
尝试:
> min(as.character(df[df$col2==min(df$col2),1]))
[1] "a"
解释:
# first find col1 list in rows with minimum of df$col2
> xx = df[df$col2==min(df$col2),1]
> xx
[1] e b a
Levels: a b c d e
# Now find the minimum amongst these after converting factor to character:
> min(as.character(xx))
[1] "a"
>
答案 1 :(得分:0)
我想你想要order
with(df, col1[order(col2, col1)][1])
# [1] a
# Levels: a b c d e
或
as.character(with(df, col1[order(col2, col1)][1]))
# [1] "a"
您可以使用
按第2列中的有序值对第1列进行排序df[with(df, order(col2, col1)),]
# col1 col2
# 5 a 1
# 4 b 1
# 3 e 1
# 1 c 2
# 2 d 3