简体   繁体   中英

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

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM