Reputation: 159
I have binary matrix A and I want to randomly change 20 percent of zero entries of it to 1. Can someone can help me with this?
Upvotes: 0
Views: 40
Reputation: 10473
Try this:
m <- matrix(seq(1:100), nrow = 20, ncol = 5)
m[sample(length(m), round(length(m) * 0.2))] <- 0
Upvotes: 2
Reputation: 886948
We can try
i1 <- m1==0
m1[sample(which(i1), round(sum(i1)*0.20))] <- 1
set.seed(24)
m1 <- matrix(sample(0:1, 5*4, replace=TRUE), ncol=5)
Upvotes: 2
Reputation: 21497
You can try the following:
set.seed(42)
dat <- sample(0:1, 40, replace = TRUE)
mat <- matrix(dat, nrow = 5) # 5x8 sample Matrix
ind <- which(mat == 0) # Gives you the indices of all zeros in the matrix
ind_to_change <- sample(ind, floor(length(ind)*0.2)) # sample 20% of the indices
mat[ind_to_change] <- 1 # set the samples indices to 1
Upvotes: 2