R中数据帧的排序

时间:2016-07-16 12:30:19

标签: r

我尝试在R中排序数据框但无法这样做。我有4列的数据框,并希望从第1列排序数据框。任何想法,我如何从第一列的条目中排序数据框?

2 个答案:

答案 0 :(得分:2)

We can also use data.table. Convert the 'data.frame' to 'data.table' (setDT(my.data) and set the 'key' as "y"

library(data.table)
setDT(my.data, key = "y")
my.data
#            y x1    x2 X3
#1: -0.96730746  5 FALSE  e
#2: -0.31570803  2  TRUE  b
#3: -0.15321836  1  TRUE  a
#4: -0.08600789  3 FALSE  c
#5:  1.83347490  4 FALSE  d

NOTE: data taken from @gung's post.

答案 1 :(得分:1)

您使用?order(另请参阅herehere)。考虑:

set.seed(5443)
(my.data <- data.frame(y=rnorm(5), 
                      x1=c(1:5), 
                      x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
                      X3=letters[1:5]))
#             y x1    x2 X3
# 1 -0.15321836  1  TRUE  a
# 2 -0.31570803  2  TRUE  b
# 3 -0.08600789  3 FALSE  c
# 4  1.83347490  4 FALSE  d
# 5 -0.96730746  5 FALSE  e
(my.data <- my.data[order(my.data[,1]),])
#             y x1    x2 X3
# 5 -0.96730746  5 FALSE  e
# 2 -0.31570803  2  TRUE  b
# 1 -0.15321836  1  TRUE  a
# 3 -0.08600789  3 FALSE  c
# 4  1.83347490  4 FALSE  d