permuting columns of a matrix with replacement and clustering
-
31-05-2021 - |
Question
How can I permute the columns of a matrix with replacement in R? I found one function called rmperm {sna} but it permutes both columns and rows whereas I just want to permute my columns.
Edit: I have to permute the matrix 1000 times and then do hierarchical clustering so I have the final tree after 1000 randomizations.
Many thanks.
Solution
Try the sample()
function.
> m <- matrix(as.integer(runif(9,0,9)),ncol=3)
> m
[,1] [,2] [,3]
[1,] 5 0 5
[2,] 6 0 0
[3,] 2 1 3
> permuted <- m[,sample(ncol(m), 10, replace=TRUE)]
> permuted
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 5 0 5 5 5 5 0 5 5 5
[2,] 0 0 0 0 6 0 0 0 6 0
[3,] 3 1 3 3 2 3 1 3 2 3
The first argument to sample()
specifies the range of the sample (1:x
), the second argument specifies the number of items to choose (size
), and the replace
parameter specifies whether or not we want to use replacement (required if size > x).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow