简体   繁体   English

在 R 中生成一个包含 pdf 的函数

[英]Generating a function in R incorporating a pdf

How would I generate function y=2+3*xi+ei where ei=iidN(0,3^2) in R?我将如何在 R 中生成函数 y=2+3*xi+ei 其中 ei=iidN(0,3^2) ? I then want to plot and apply a linear regression model against it using x, which is just a simple sequence of data然后我想使用 x 绘制并应用线性回归模型,这只是一个简单的数据序列

Define function定义函数

f <- function(x, a=2, b=3) a + b * x + rnorm(length(x), mean=0, sd=3^2)

Generate some points产生一些点

set.seed(123)
data <- data.frame(x=0:10, y=f(0:10))

Fit linear model拟合线性模型

fit <- lm(y~x, data=data)
summary(fit)
#Call:
#lm(formula = y~x, data=data)
#
#Residuals:
#    Min      1Q  Median      3Q     Max
#-12.832  -6.181  -1.144   6.220  13.823
#
#Coefficients:
#            Estimate Std. Error t value Pr(>|t|)
#(Intercept)    4.027      5.183   0.777   0.4570
#x              2.917      0.876   3.330   0.0088 **
#---
#Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
#Residual standard error: 9.188 on 9 degrees of freedom
#Multiple R-squared:  0.552,    Adjusted R-squared:  0.5022
#F-statistic: 11.09 on 1 and 9 DF,  p-value: 0.008802

We see large uncertainty in (Intercept) due to large error term.由于大的误差项,我们看到(Intercept)很大的不确定性。

Show data and fit显示数据和拟合

ggplot(data, aes(x=x, y=y)) +
  geom_point() +
  geom_smooth(method='lm', formula=y~x)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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