R.K.
R.K.

Reputation: 41

How can I order a column of a matrix?

I have created a matrix out of two vectors

x<-c(1,118,3,220)
y<-c("A","B","C","D")
z<-c(x,y)
m<-matrix(z,ncol=2)

Now I want order the second row, but it doesn't work properly. I tried:

m[order(m[,2]),]

The order should be 1,3,118,220, but it shows 1,118,220,3

Upvotes: 1

Views: 41

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388862

The matrix can only hold one class which in this case would be character since you have "A","B","C","D".

So if still want to order the rows in matrix you need to subset the first column convert it into numeric, use order and then use them to reorder rows.

m[order(as.numeric(m[, 1])), ]

#    [,1]  [,2]
#[1,] "1"   "A" 
#[2,] "3"   "C" 
#[3,] "118" "B" 
#[4,] "220" "D" 

Since you have data with mixed data types why not store them in dataframe instead ?

x<-c(1,118,3,220)
y<-c("A","B","C","D")
df <- data.frame(x,y)
df[order(df[,1]),]

#    x y
#1   1 A
#3   3 C
#2 118 B
#4 220 D

Upvotes: 1

Related Questions