Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

r - Reorder a column in a dataframe to a specified order

I have a data frame, where every row has a value, and every block of 100 rows has an index (between 1 and 10). I would like to sort the index blocks in a particular order, but am unsure how to do that:

N=1000
value = runif(N, min=0, max=100)
index = rep(1:10, each=100)
DF=data.frame(value,index)
ord = c(1,4,6,3,7,9,8,2,5,10)

So basically, I would like the index column of DF to be ordered in blocks of the order specified in ord, instead of the index column of DF being ordered as 1,2,3,4,5,6,7,8,9,10.

Any advice would be appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could simply convert index to factor and set the levels as in ord order and then sort the data as in

DF$index <- factor(DF$index, levels = ord)
DF[order(DF$index), ]

If you don't want to "alter your original data" you could simply create a separate index as in

indx <- factor(DF$index, levels = ord) 
DF[order(indx), ]

Additional otion is to order your data set by reference using setorder from the data.table package

library(data.table)
setorder(setDT(DF)[, index := factor(index, levels = ord)], index)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...