How to add a random value to a vector with the standard deviation depending on the value in R

StackOverflow https://stackoverflow.com/questions/20575342

  •  01-09-2022
  •  | 
  •  

Question

It's difficult to phrase the title of this question, but what is have, is a xts vector:

> test
                    E1      E2      E3     E4   FP5
2012-05-17 03:34:37 4045.75 4045.75 2835.5 1292 171.9

Now, I want to add the result of a normal distribution to each value of test but I want the sd argument (the standard deviation) to be the sqrt of the value itself

For isntance, in a non automated method I would have:

test$E1 = test$E1 + rnorm(1, sd = sqrt(test$E1))
test$E2 = test$E2 + rnorm(1, sd = sqrt(test$E2))
...

Any way to do this in a simpler way?

Was it helpful?

Solution

You can do this with apply, called on the columns of test:

test = apply(test, 2, function(x) x+rnorm(length(x), sd=sqrt(x)))

Longer form (without one-line function syntax):

adjust.values = function(x) {
  return(x + rnorm(length(x), sd=sqrt(x)))
}
test = apply(test, 2, adjust.values)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top