Home > Enterprise >  uniform distribution value on [−0.6, −0.3] ∪ [0.3, 0.6] in R
uniform distribution value on [−0.6, −0.3] ∪ [0.3, 0.6] in R

Time:08-27

I have a binary matrix with 0 and 1s and I want each non-zero element substituted by a uniform distribution value on [−0.6, −0.3] ∪ [0.3, 0.6] in R.

Can anyone please help how can I achieve this?

CodePudding user response:

Yes sample(c(1,-1),100,replace=T)*runif(100,0.3,0.6).

CodePudding user response:

If your binary matrix looks like this:

set.seed(1)
m <- matrix(rbinom(16, 1, 0.5), 4)

m
#>      [,1] [,2] [,3] [,4]
#> [1,]    0    0    1    1
#> [2,]    0    1    0    0
#> [3,]    1    1    0    1
#> [4,]    1    1    0    0

Then you can replace its elements like so:

m[m != 0] <- runif(sum(m), 0.3, 0.6) * sign(rnorm(sum(m)))

m
#>            [,1]       [,2]      [,3]      [,4]
#> [1,]  0.0000000  0.0000000 0.3636428 0.4955021
#> [2,]  0.0000000  0.4140106 0.0000000 0.0000000
#> [3,] -0.5152856 -0.5332336 0.0000000 0.3376665
#> [4,] -0.5975718 -0.5804116 0.0000000 0.0000000
  • Related