Search code examples
rmatrixrandomsamplenormal-distribution

replacing columns in matrix from existing matirx R


I want to ask you a quastion how to replace some percentage of columns in Y matrix with columns form X matrix using function sample ? So I have two matrixes X and Y and I want to replace for example 20 percent of columns (randomly) form matrix X to matrix Y using sample ? Please do you have any ideas.


Solution

  • Try this (20% of m1 is replaced by m2 of the same indices):

    m1 <- matrix(1, ncol = 10, nrow = 10)
    m2 <- matrix(2, ncol = 10, nrow = 10)
    
    s  <- sample(1:length(m1), length(m1)*0.2) 
    m1[s] <- m2[s]