Change Row Order in a Matrix/Dataframe

Change row order in a matrix/dataframe

There probably are more elegant ways, but this works:

m <- matrix(1:9, ncol=3, byrow=TRUE)

# m[rev(seq_len(nrow(m))), ] # Initial answer
m[nrow(m):1, ]
[,1] [,2] [,3]
[1,] 7 8 9
[2,] 4 5 6
[3,] 1 2 3

This works because you are indexing the matrix with a reversed sequence of integers as the row index. nrow(m):1 results in 3 2 1.

How can I reorder the rows of a matrix, data.frame or vector according to another one


test2 <- test2[rownames(test1),,drop=FALSE]

Changing row order in pandas dataframe without losing or messing up data

For reindex is necessary create index from sample column:

df=df.set_index(['sample']).reindex(["CO ref","CO tus","CO raai"]).reset_index()

Or use ordered categorical:

cats = ["CO ref","CO tus","CO raai"]
df['sample'] = pd.CategoricalIndex(df['sample'], ordered=True, categories=cats)
df = df.sort_values('sample')

How do I change columns in the same order as in my order matrix, per row

Using base R you could loop over the matrix rows and assign the values from your df.responses by selecting the column order by the matrix row values:

# copy df.responses so we won't grow an object in the loop
df.result <- df.responses
# Rename the columns as they won't be correct after
colnames(df.result) <- c("V1","V2","V3")

for (x in 1:nrow(order.matrix)) {
# replace the line with the value ordered by the matrix line names
df.result[x,] <- df.responses[x,order.matrix[x,]]
}

R: Change row order

One way to do it is to index the row directly:

df[c("X2","X1"),]

Or you could use the row indices:

df[c(2,1),]  # or just df[2:1,]

How to convert a matrix looking dataframe with row and column labels to a regular pandas dataframe?

using melt and str.cat

s = data.reset_index().melt(id_vars='index').sort_values('index')
s['index'] = s['index'].str.cat(s['variable'],sep='-')
s = s.drop('variable',axis=1)

print(s)

index value
0 a-d 1.0
3 a-e 1.0
6 a-f 3.0
1 b-d 2.0
4 b-e 1.0
7 b-f 4.0
2 c-d 2.0
5 c-e 3.0
8 c-f 0.8

Edit

Cosider this simpler solution as proposed by our resident genius anky using .pop in conjunction with str.cat

s = data.reset_index().melt(id_vars='index').sort_values('index')
s['index'] = s['index'].str.cat(s.pop('variable'),sep='-')

print(s)

index value
0 a-d 1.0
3 a-e 1.0
6 a-f 3.0
1 b-d 2.0
4 b-e 1.0
7 b-f 4.0
2 c-d 2.0
5 c-e 3.0
8 c-f 0.8

Sorting the values inside row in a data frame, by the order of its factor levels?

In your code, the issue is happening at this line.

arcana_table <- as.data.frame(matrix(shuffled_arcana, nrow = 5, ncol = 5))

shuffled_arcana is a factored vector but you cannot have a factor-matrix so it changes the vector from factor to character and hence, sorting does not happen as desired.

Here's a way -

set.seed(2022)

arcanaVector <- c(rep("Supreme", 3),
rep(c("Good", "Moderate", "Poor", "Awful"), each = 5),
rep("Worst", 2))
arcanaLevels <- c("Supreme", "Good", "Moderate", "Poor", "Awful", "Worst")
shuffled_arcana <- sample(arcanaVector)
arcana_table <- matrix(shuffled_arcana,nrow = 5, ncol = 5)
row.names(arcana_table) <- c("Presence", "Manner", "Expression", "Complexity", "Tradition")

arcana_table <- apply(arcana_table, 1, function(x) sort(factor(x, arcanaLevels))) |>
t() |>
as.data.frame()

arcana_table

# V1 V2 V3 V4 V5
#Presence Good Good Good Good Awful
#Manner Supreme Moderate Poor Awful Awful
#Expression Supreme Supreme Moderate Moderate Poor
#Complexity Moderate Moderate Poor Poor Worst
#Tradition Good Poor Awful Awful Worst

If you want to change a specific row you may use -

arcana_table[1, ] <- as.character(sort(factor(arcana_table[1, ], arcanaLevels))) 

How to reverse rows in matrix?

We can combine apply() and rev() to the matrix n and rearrange the entries:

n <- matrix(1:25, 5, byrow = TRUE)
apply(n,2,rev)
# [,1] [,2] [,3] [,4] [,5]
#[1,] 21 22 23 24 25
#[2,] 16 17 18 19 20
#[3,] 11 12 13 14 15
#[4,] 6 7 8 9 10
#[5,] 1 2 3 4 5

By using apply() with the second parameter (the margin) equal to 2 we loop through all the columns of n, and for each column we apply the function rev(), which reverses the entries of a vector.


A more compact and faster way to obtain the same result is the solution pointed out by @Cath:

n[nrow(n):1,]

This simply reverses the order of the rows in the matrix.



Related Topics



Leave a reply



Submit