Je voudrais classer la ligne d'une base de données (avec 30 colonnes) qui a des valeurs numériques allant de -inf à + inf. Voici ce que j'ai
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
C'est ce que j'aimerais avoir:
> df_rank
StockA StockB StockC
1 3 1 2
2 1 2 3
3 1 3 2
J'utilise cette commande:
> rank(df[1,])
StockA StockB StockC
2 3 1
Les variables de classement résultantes ne sont pas correctes, comme vous pouvez le constater.
Réponses:
1 pour la réponse № 1rank()
assigne le rang le plus bas à la plus petite valeur. La réponse courte à votre question est donc d'utiliser le rang du vecteur multiplié par -1:
rank (-c(-5, 2, -3) )
[1] 1 3 2
Voici le code complet:
# 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