需要编写一个用户定义的R函数,该函数将从包括测量误差项的以下函数中生成观测数据,其中从均值为0和标准偏差为1+ ||的正态分布中随机抽取。通过从−4和4之间的均匀分布中随机绘制来在数据集中创建值。生成2,000个观察值:{(,),= 1..2000}。
() = {1, if =0
sin()/, otherwise}
请协助
答案 0 :(得分:1)
观察 功能以 lambda 作为参数。这将带您进入:
set.seed(101)
x <- runif(n= 2000, min= -4*pi, max = 4*pi)
observations <- function(lambda) {
e <- sapply(x, function(x) { # error term one for each x
e <- rnorm(1, mean = 0, sd = lambda/(1+ abs(x)))
return(e) } )
y_fx <- ifelse(x == 0, 1, sin(x)/x) + e
return(list(x = x, y = y_fx))
}
obs_5 <- observations(5) # observations for lambda = 5
obs_0.5 <- observations(0.5) # for lambda = 0.5
plot(obs_5$x,obs_5$y, col = 'red' , xlab = "X(i)", ylab = "Y(i)")
points(obs_0.5$x,obs_0.5$y, col = "blue") # lambda = 0.5, blue points