I tried sorting data frame in R but unable to do so. I have data frame of 4 columns and would like to sort the data frame from 1st column. Any idea, how Can i sort data frame from entries of first column?
Asked
Active
Viewed 275 times
-5
-
See `?order`. That should get you started. There are plenty of similar questions on SO. – lmo Jul 16 '16 at 12:35
2 Answers
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.

akrun
- 874,273
- 37
- 540
- 662
1
You use ?order (see also here, and here). Consider:
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

Community
- 1
- 1

gung - Reinstate Monica
- 11,583
- 7
- 60
- 79
-
-
(I must have mis-copied somehow. It's fixed now.) All columns are in a different order, @QuantTrader. See the links for how `order` works & how to sort. – gung - Reinstate Monica Jul 16 '16 at 13:14