我有下面的df
df <-dput(l)
structure(list(l = c(7.4, 7, 6.7, 8.8, 7.3, 9.1, 7.7, 9.5, 7.5,
7.4, 6.7, 7.3, 7.5)), row.names = c("rankings_message_1", "rankings_message_2",
"rankings_message_3", "rankings_message_4", "rankings_message_5",
"rankings_message_6", "rankings_message_7", "rankings_message_8",
"rankings_message_9", "rankings_message_10", "rankings_message_11",
"rankings_message_12", "rankings_message_13"), class = "data.frame")
但我想添加一列來對數字(它們是 %)進行排名,其中最高的 # 將被標記為排名 1,依此類推。
我試過這個,但我得到一個錯誤:
df$Rank <- rank(desc(df))
uj5u.com熱心網友回復:
您可能已經加載tidyverse
而沒有將其包含在您的代碼中。到達那里的另一種方法是
df$Rank <- (nrow(df) 1) - rank(df$l)
df[order(Rank), ]
# l Rank
# rankings_message_8 9.5 1.0
# rankings_message_6 9.1 2.0
# rankings_message_4 8.8 3.0
# rankings_message_7 7.7 4.0
# rankings_message_9 7.5 5.5
# rankings_message_13 7.5 5.5
# rankings_message_1 7.4 7.5
# rankings_message_10 7.4 7.5
# rankings_message_5 7.3 9.5
# rankings_message_12 7.3 9.5
# rankings_message_2 7.0 11.0
# rankings_message_3 6.7 12.5
# rankings_message_11 6.7 12.5
uj5u.com熱心網友回復:
我想這只是
rev(rank(df$l)) # which is wrong, should have been `rank(-df$l)`
默認情況下,對關系的處理是“平均”的,但是如果您希望至少有一個關系, 1
那么您可以選擇。看?rank
rev(rank(df$l))
#[1] 8.5 4.5 1.5 6.5 8.5 13.0 10.0 12.0 4.5 11.0 1.5 3.0 6.5
?desc # you appear to be using a package that is not base R.
#No documentation for ‘desc’ in specified packages and libraries:
#you could try ‘??desc’
?rank
rev(rank(df$l, ties="first"))
#[1] 9 5 2 7 8 13 10 12 4 11 1 3 6
我不明白為什么 1 出現在 2 之后,然后我開始懷疑這段代碼的正確性。我認為應該改為:
(df$r1 <- abs( rank(df$l, ties="first") - (length(df$l) 1)) )
# [1] 8 11 13 3 10 2 4 1 6 7 12 9 5
還可以對向量的負數進行排序:
df$r2 <- rank(-df$l, ties="last")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505737.html