hard worker
hard worker

Reputation: 191

how to calculate one value is in the some range in r?

I have a vector which is interval

a=c((0.5)-rnorm(1,1,0.5),(0.5)+rnorm(1,1,0.5))

I want to repeat generate a 100 interval like above, and calculate how

many times (proportion) 1 appears in these 100 samples.

for example:-0.9243532 0.7800040. 1 is not in this interval. so return false. -0.6741866 1.4794725. 1 is in this interval , so return true. I want the proportion of 100 of them. the ratio : # of true/100

May be show how to calculate the bollean result for 1 is in one interval is also help

Upvotes: 1

Views: 98

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 101099

Your math representation actually can be simplified a bit and you can try the code below

> mean(replicate(100, prod(0.5 + rnorm(2, 1, 0.5) * c(-1, 1)) < 0))
[1] 0.85

If you want to speed up, you can try

> n <- 100
> mean(do.call(`*`, split(0.5 + rnorm(2 * n, 1, 0.5) * c(-1, 1), c(1, 2))) < 0)
[1] 0.84

Upvotes: 1

akrun
akrun

Reputation: 886948

We can use replicate in base R

m1 <- t(replicate(100, c((0.5)-rnorm(1,1,0.5),(0.5)+rnorm(1,1,0.5)), simplify = TRUE))
mean(m1[,1] <=1 & m1[,2] > 1)
[1] 0.8

Upvotes: 2

AnilGoyal
AnilGoyal

Reputation: 26218

you may also use map_lgl

library(tidyverse)
set.seed(1)
map_lgl(replicate(100, c((0.5)-rnorm(1,1,0.5),(0.5)+rnorm(1,1,0.5)), simplify = FALSE), ~ 1 >= .x[1]  & 1 <= .x[2])
#>   [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE
#>  [13]  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
#>  [25]  TRUE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
#>  [37]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
#>  [49]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
#>  [61]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE
#>  [73]  TRUE  TRUE FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
#>  [85]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE
#>  [97]  TRUE FALSE FALSE  TRUE

For proportion

library(tidyverse)
set.seed(1)
n <- 100
sum(map_lgl(replicate(n, c((0.5)-rnorm(1,1,0.5),(0.5)+rnorm(1,1,0.5)), simplify = FALSE), ~ 1 >= .x[1]  & 1 <= .x[2]))/n
#> [1] 0.86

Upvotes: 2

Related Questions