学习使用 R 简单回归分析

回归分析有多种(线性,多项式等),这里对高中时期的线性回归分析 R 实现做一个笔记。

R 中有现成的方法实现。

拟对肥胖程度与高血压数据进行回归,数据参考:

https://people.sc.fsu.edu/~jburkardt/datasets/iswr/bp.obese.csv

linear_regression.R

#!/usr/bin/env Rscript
###
# Simple linear regression using R
#
# @author YanWen <i@yanwen.email>
###

bo <- read.csv('bp.obese.csv')

# Plot
plot(BloodPressure ~ Obese, data=bo, pch=as.integer(Sex), col=as.integer(Sex) + 3)
legend('topright', legend=c('Male', 'Female'), pch=c(1, 2), col=c(3, 4))

# Linnear regression
m1 <- lm(BloodPressure ~ Obese, data=bo)
abline(m1, col='red', lty=2, lwd=3)

# Simple prediction
predict(m1, data.frame('Obese' = 5.0))
# ->
#        1
# 211.8247

predict(m1, data.frame('Obese' = 5.0), interval='prediction')
# ->
#        fit      lwr     upr
# 1 211.8247 152.1204 271.529

线性回归的系数参考 m1 变量,作图:

参考:

  1. R doc(?lm or https://cran.r-project.org/doc/manuals/r-release/fullrefman.pdf P.1422)
  2. https://en.wikipedia.org/wiki/Regression_analysis

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s