r - 如何置换给定矩阵的行
问题描述
早上好 !
假设我们有以下矩阵:
m=matrix(1:18,ncol=2)
print("m : before")
print(m)
[1] "m : before"
[,1] [,2]
[1,] 1 10
[2,] 2 11
[3,] 3 12
[4,] 4 13
[5,] 5 14
[6,] 6 15
[7,] 7 16
[8,] 8 17
[9,] 9 18
例如,我想置换一些行:
tmp=m[8:9,]
m[8:9,]=m[3:4,]
m[3:4,]=tmp
这与:
# indices to permute
before=8:9
after=3:4
tmp=m[before,]
m[before,]=m[after,]
m[after,]=tmp
[1] "after"
[,1] [,2]
[1,] 1 10
[2,] 2 11
[3,] 8 17
[4,] 9 18
[5,] 5 14
[6,] 6 15
[7,] 7 16
[8,] 3 12
[9,] 4 13
我想知道是否有任何包可以使此类任务自动化。目前,我不愿意使用用户定义的函数。
谢谢你的帮助 !
解决方案
我认为最简单的解决方案就是使用base
r 函数,例如sample
:
set.seed(4)
m[sample(1:nrow(m),nrow(m)),]
这给了你:
[,1] [,2]
[1,] 8 17
[2,] 3 12
[3,] 9 18
[4,] 7 16
[5,] 4 13
[6,] 6 15
[7,] 2 11
[8,] 1 10
[9,] 5 14
如果你只想置换一些行,你可以这样做:
m[7:9,] <- m[sample(7:9,3),]#where the last number (3) is the number of row
to permute
哪个给你
[,1] [,2]
[1,] 1 10
[2,] 2 11
[3,] 3 12
[4,] 4 13
[5,] 5 14
[6,] 6 15
[7,] 7 16
[8,] 9 18
[9,] 8 17
推荐阅读
- c# - 使用 Windows 窗体处理通知
- node.js - 将 JS 注入到具有匹配文件名的 HTML 页面中
- php - 允许客户在 WooCommerce 中更改订单状态
- node.js - 控制台中的节点打印 [Circular]
- torch - 我找不到使用 torch.autograd.set_detect_anomaly(True) 的就地操作
- javascript - 一旦反应应用程序状态改变,谷歌地图不会更新
- python - 如何更改代码以获取 IoU 值?
- reactjs - 如何使用功能组件和 react-redux 取消订阅 firebase?
- kubernetes - 错误:Kubernetes 集群无法访问:获取“http://localhost:8080/version?timeout=32s”:拨打 tcp 127.0.0.1:8080:连接:连接被拒绝
- excel - 使用 VBA 在用户窗体上生成组合框和编辑文本框