首页 > 解决方案 > 如何置换给定矩阵的行

问题描述

早上好 !

假设我们有以下矩阵:

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

我想知道是否有任何包可以使此类任务自动化。目前,我不愿意使用用户定义的函数。

谢谢你的帮助 !

标签: r

解决方案


我认为最简单的解决方案就是使用baser 函数,例如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

推荐阅读