replacing randomly values in an existing matrix in R

后端 未结 2 1909
独厮守ぢ
独厮守ぢ 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.

提交回复
热议问题