Robbie Voort
Robbie Voort

Reputation: 141

Rearrange rownames of data.frame (non alphabetic)

set0 <- data.frame(A = c("A", "B", "C", "D", "A", "B", "C", "D", "A", "B"),
                   B = c("E", "F", "G", "H", "I", "E", "F", "G", "H", "I"))

set0 <- table(set0)

result:
> set0
   B
A   E F G H I
  A 1 0 0 1 1
  B 1 1 0 0 1
  C 0 1 1 0 0
  D 0 0 1 1 0

I know that when I want to change the column order I can use the following:

set0 <- set0[, c(5, 4, 3, 2, 1)]

The above makes it possible to change the order of the column in any way I like.

I am looking for something that makes it possible to do the exact same but for the rownames. Any ideas?

Upvotes: 1

Views: 76

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101403

You can use factor to define the order, e.g.,

table(
  transform(
    set0,
    A = factor(A, levels = sort(unique(A), decreasing = TRUE))
  )
)

which gives

   B
A   E F G H I
  D 0 0 1 1 0
  C 0 1 1 0 0
  B 1 1 0 0 1
  A 1 0 0 1 1

Upvotes: 0

jay.sf
jay.sf

Reputation: 72891

In the brackets, columns are defined to the right of the comma (that what you did). In case you didn't know yet, rows are defined to the left of the comma. So you can use one of these approaches that you like best:

set0[c(4, 3, 2, 1), ]

set0[4:1, ]

set0[rev(seq(nrow(set0))), ]

set0[c("D", "C", "B", "A"), ]

set0[rev(rownames(set0)), ]

#    B
# A   E F G H I
#   D 0 0 1 1 0
#   C 0 1 1 0 0
#   B 1 1 0 0 1
#   A 1 0 0 1 1

Upvotes: 2

Related Questions