It's difficult to phrase the title of this question, but what is have, is a xts vector:
很难说出这个问题的标题,但有什么,是一个xts向量:
> 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
现在,我想将正态分布的结果添加到每个测试值,但我希望sd参数(标准偏差)是值本身的sqrt
For isntance, in a non automated method I would have:
对于isntance,在非自动化方法中我会:
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?
有没有办法以更简单的方式做到这一点?
1 个解决方案
#1
2
You can do this with apply, called on the columns of test:
您可以使用apply,在测试列上调用:
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)
#1
2
You can do this with apply, called on the columns of test:
您可以使用apply,在测试列上调用:
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)