R语言在统计分析方面有着丰富的功能和包。下面是一个简单的统计示例,使用内置的数据集和一些常见的统计包。

线性回归分析

数据准备
# 使用内置数据集mtcars
data(mtcars)

运行线性回归
# 安装并加载lmtest和car包
install.packages(c("lmtest", "car"))
library(lmtest)
library(car)

# 运行线性回归
model <- lm(mpg ~ wt + hp, data = mtcars)

# 显示回归结果
summary(model)

绘制散点图和回归线
# 安装并加载ggplot2包
install.packages("ggplot2")
library(ggplot2)

# 绘制散点图和回归线
ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, col = "blue") +
  labs(title = "Scatterplot and Regression Line", x = "Weight", y = "MPG")

描述性统计
# 使用summary函数显示数据的描述性统计
summary(mtcars$mpg)

t检验
# 使用t.test函数进行两组样本的t检验
# 示例:比较两组汽车的mpg
group1 <- mtcars$mpg[mtcars$cyl == 4]
group2 <- mtcars$mpg[mtcars$cyl == 6]

t_test_result <- t.test(group1, group2)
t_test_result

这只是一个简单的例子,涵盖了一些基本的统计分析,包括线性回归、绘图、描述性统计和t检验。R语言拥有众多强大的统计包,你可以根据你的需求选择合适的包进行更复杂的统计分析。在实际工作中,具体的统计方法和分析步骤将根据你的数据和研究问题而变化。


转载请注明出处:http://www.pingtaimeng.com/article/detail/6415/R语言