0

I am trying to reorder a data frame in R. The data frame is a 264x264 correlation matrix. I have a numeric vector (1:264) which contains the order that I want the rows and columns of my data frame to match.

I've tried using df[order(list),] and df[,order(list)] to sort the rows and columns. While the rows and columns reorder, it is not to the expected order. For instance, if the first three columns were supposed to be 73, 85, and 66, I instead get 224, 95, and 135.

names(df) <- c(1:ncol(df))
row.names(df) <- c(1:nrow(df))

df2 <- df[order(order.vector),]

df2 <- df2[,order(order.vector)]

The rows and columns of the data frame should be in the same order as the numbers in my list (order.vector).

steveb
  • 5,382
  • 2
  • 27
  • 36
  • What is the numeric vector that contains the order that you want? Is it order.vector? Is the call to the function order( ) messing you up? – Joe Aug 01 '19 at 23:36
  • When you say that the rows AND columns should be in the same order as the numbers in your list, do you mean that if order.vector = c(2,3, 1), then you want the 2nd row to be 1st, and the 3rd row to be 2nd, and the 1st row to be last? And do you want the same to be true of the columns, at the same time? If so, I think df2[order.vector,order.vector] will work. – Joe Aug 01 '19 at 23:45
  • Something like this may help you: https://stackoverflow.com/questions/46129322/arranging-rows-in-custom-order-using-dplyr – GUANHUA HUANG Aug 01 '19 at 23:46
  • Great! You’re welcome. – Joe Aug 02 '19 at 01:52

0 Answers0