r фрейм данных с использованием ранга - PullRequest
0 голосов
/ 05 мая 2018

Я бы хотел ранжировать строку кадра данных (с 30 столбцами), который имеет числовые значения в диапазоне от -inf до + inf. Вот что у меня есть:

   df <- structure(list(StockA = c("-5", "3", "6"), 
                  StockB = c("2", "-1", "3"), 
                  StockC = c("-3", "-4", "4")), 
             .Names = c( "StockA","StockB", "StockC"),
             class = "data.frame", row.names = c(NA, -3L))

    > df
        StockA StockB StockC
    1     -5      2     -3
    2      3     -1     -4
    3      6      3      4

Вот что я хотел бы иметь:

 > df_rank
     StockA StockB StockC
 1      3      1      2
 2      1      2      3
 3      1      3      2

Я использую эту команду:

 > rank(df[1,])
 StockA StockB StockC 
 2      3      1

Полученные ранговые переменные неверны, как вы можете видеть.

1 Ответ

0 голосов
/ 06 мая 2018

rank() присваивает самый низкий ранг наименьшему значению. Итак, короткий ответ на ваш вопрос - использовать ранг вектора, умноженный на -1:

rank (-c(-5, 2, -3) )
[1] 1 3 2

Вот полный код:

# data frame definition. The numbers should actually be integers as pointed out
# in comments, otherwise the rank command will sort them as strings 
# So in the real word you should define them as integers, 
# but to go with your data I will convert them to integers in the next step
df <- structure(list(StockA = c("-5", "3", "6"), 
                     StockB = c("2", "-1", "3"), 
                     StockC = c("-3", "-4", "4")), 
                .Names = c( "StockA","StockB", "StockC"),
                class = "data.frame", row.names = c(NA, -3L))

# since you plan to rank them not as strings, but numbers, you need to convert
# them to integers:
df[] <- lapply(df,as.integer)

# apply will return a matrix or a list and you need to 
# transpose the result and convert it back to a data.frame if needed
result <- as.data.frame(t( apply(df, 1, FUN=function(x){ return(rank(-x)) }) ))

result
#  StockA StockB StockC
#       3      1      2
#       1      2      3
#       1      3      2
...