首页 > 解决方案 > 如何订购矩阵的一列?

问题描述

我用两个向量创建了一个矩阵

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

现在我想订购第二行,但它不能正常工作。我试过了:

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

顺序应该是 1,3,118,220,但显示的是 1,118,220,3

标签: rmatrix

解决方案


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

推荐阅读