r - 如何订购矩阵的一列?
问题描述
我用两个向量创建了一个矩阵
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
解决方案
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
推荐阅读
- android - Android 10 MediaStore update image RecoverableSecurityException
- python - Psycopg2-binary 安装问题
- git - 构建 Chromium 版本号 60
- msbuild - 将 .dll 引用添加到构建之前生成的 nuget
- reactjs - 无法从类组件访问 redux 状态
- php - 使用 RESO spark Web API 未发生数据复制
- angular - Dropdown in angular6 for a menu not working
- git - 将我的项目推送到github之前需要隐藏哪些信息
- php - 如何在 PHP Apache 中通过 DSN 连接 SQL Server?(当 Apache 服务开启时它不工作)
- javascript - CKAN“autocomplete.js”模块不工作(CKAN 2.8 版)