R - how to re-order data frame by row index number

2019-04-26 14:11发布

问题:

This may be a very basic question but I could't find it. Let's say I have a data frame d with row numbers in disorder like this:

    Signal
4   9998
3   549
1   18
5   2.342
2   0.043

How can I sort this by increasing row index numbers to obtain the following?

    Signal
1   18
2   0.043
3   549
4   9998
5   2.342

回答1:

d <- read.table(text=readClipboard(), header=TRUE)    
d$index <- as.numeric(row.names(d))
d[order(d$index), ]


回答2:

you can also use this :

 d[order(as.numeric(rownames(d))),,drop=FALSE]

drop is useful only if your data.frame has one column otherwise remove it



回答3:

rownames(d) <- 1 : length(rownames(d))