How to swap a number of the values between 2 rows

2019-06-10 05:27发布

问题:

I have a matrix with the size of 10x100. How can I swap the values between row 1 and row 2 in the first 30% of the columns?

回答1:

We can just reverse the row index for the 1st two rows along along with column index created by taking the sequence of rounded 30% total number of columns for swapping the values in the rows.

colS <- seq(round(ncol(m1)*0.3))
m1[2:1, colS] <- m1[1:2, colS]

data

m1 <- matrix(1:1000, 10, 100)