首页 > 解决方案 > 在 R 中生成包含 pdf 的函数

问题描述

如何在 R 中生成函数 y=2+3*xi+ei where ei=iidN(0,3^2)?然后我想使用 x 绘制并应用线性回归模型,这只是一个简单的数据序列

标签: rrstudio

解决方案


定义函数

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

产生一些点

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

拟合线性模型

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

(Intercept)由于大的误差项,我们看到了很大的不确定性。

显示数据和拟合

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

在此处输入图像描述


推荐阅读