replacing randomly values in an existing matrix in R

后端 未结 2 1885
独厮守ぢ
独厮守ぢ 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条回答
  • 2021-01-20 05:01

    you must apply runif in the right spot, which is the index to vec. (The way you have it now, you are asking R to draw random numbers from a uniform distribution between NA and NA, which of course does not make sense and so it gives you back NaNs)

    Try instead:

            N  <-  5                                   # the number of random values to replace
          inds <- round ( runif(N, 1, length(vec)) )   # draw random values from [1, length(vec)]
     vec[inds] <- NA                                   # use the random values as indicies to vec, for which to replace
    

    Note that it is not necessary to use round(.) since [[ will accept numerics, but they will all be rounded down by default, which is just slightly less than a uniform dist.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题