replacing randomly values in an existing matrix in R

后端 未结 2 1903
独厮守ぢ
独厮守ぢ 2021-01-20 04:14

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

2条回答
  •  Happy的楠姐
    2021-01-20 05:03

    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
    

提交回复
热议问题