I have an existing matrix and I want to replace some of the existing values by NA\'s in a random uniform way.
I tried to use the following, but it only replaced 392
Try this. This will sample your matrix uniformly without replacement (so the same value is not chosen and replaced twice). If you want some other distribution, you can modify the weights using the prob
argument (see ?sample
)
vec <- matrix(1:25, nrow = 5)
vec[sample(1:length(vec), 4, replace = FALSE)] <- NA
vec
[,1] [,2] [,3] [,4] [,5]
[1,] NA 6 NA 16 NA
[2,] NA 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25