Hi All,

I have two known numbers and I want to simulate another two numbers so that the standard deviation of the 4 numbers is fixed. How can I do that in R?

Thanks!

Hi All,

I have two known numbers and I want to simulate another two numbers so that the standard deviation of the 4 numbers is fixed. How can I do that in R?

Thanks!

Just because it's possible to calculate the `sd`

of four numbers doesn't mean that one should.

```
set.seed(137)
basket <- seq(100,999,1)
my_two <- c(123,456)
new_two <- sample(basket,2)
the_four <- c(my_two,new_two)
sd(the_four)
#> [1] 230.626
```

^{Created on 2020-08-16 by the reprex package (v0.3.0)}

Not sure there is a unique solution. You might be able to derive it analytically with additional constraints. And as technocrat points, it might not make sense to compute the sd on 4 points.

Anyway, you can do it by numerical optimization:

```
fn_to_minimize <- function(new_x, x1, x2, target_sd){
abs(sd(c(x1,x2,new_x[1],new_x[2])) - target_sd)
}
optim(c(1,2), fn_to_minimize, x1 = 1, x2 = 2, target_sd = 10)$par
# [1] -11.92944 12.48387
sd(c(1, 2, -11.92944, 12.48387))
# [1] 10
```

See the documentation of `optim()`

for how it works. Also note that it may be slow if you're trying to do that a lot of times.

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.