获取变量的分组统计量 | ||||
函数 | 来源包 | 功能描述 | ||
能否获对多个变量进行分组描述 | 能否设置多个分类变量 | 能否获取指定统计量 | ||
aggregate() | stats | 能 | 能 | 能 |
tapply() | base | 否 | 否 | 能 |
summ() | epiDisplay | 否 | 否 | 否 |
describeBy() | psych | 能 | 否 | 否 |
group_by()和summarise() | dplyr | 能 | 能 | 能 |
####--------数值型变量的描述性统计分析-------------
###一、加载数据集
data(birthwt,package = "MASS")
###二、处理数据集
str(birthwt)#查看数据框结构
library(dplyr)
birthwt<-birthwt%>%#将分类变量转换为因子
mutate(low=factor(low,labels = c("no","yes")),
race=factor(race,labels = c("white","black","other")),
smoke=factor(smoke,labels = c("no","yes")),
ht=factor(ht,labels = c("no","yes")),
ui=factor(ui,labels = c("no","yes")))
str(birthwt)#查看转换后数据框结构
###三、对变量进行统计描述
#先计算这3个变量的描述性统计量,然后按照母亲吸烟情况(smoke)分组考查描述性统计量
cont.vars<-dplyr::select(birthwt,age,lwt,bwt)
##(一)获取变量基本统计量(未分组)
#1、汇总统计(有多个固定的统计量)
#函数summary() #Min、 1st Qu、Median、Mean、3rd Qu、Max,没有sd
summary(cont.vars)
#函数summ() #Min、Max、mean、median、sd
library(epiDisplay)
summ(cont.vars)
#2、选择指定统计量
#单个变量
length(cont.vars$age)#样本量
mean(cont.vars$age)#均值
sd(cont.vars$age)#标准差
#多个变量
#函数sapply
sapply(cont.vars,sd)
#函数describe
library(psych)
describe(cont.vars)#包含峰度和偏度
##(二)获取变量的分组统计量
#1、函数aggregate():第一个参数可以是数据集也可以是变量,
# 可指定统计量
#设置一个分类变量
aggregate(cont.vars,by=list(smoke=birthwt$smoke),mean)
aggregate(cont.vars$bwt,by=list(smoke=birthwt$smoke),mean)
aggregate(cont.vars,by=list(smoke=birthwt$smoke),sd)
aggregate(cont.vars$bwt,by=list(smoke=birthwt$smoke),sd)
#设置多个分类变量
aggregate(cont.vars,by=list(smoke=birthwt$smoke,
race=birthwt$race),mean)
#2、函数tapply():第一个参数必须是一个变量;
# 可指定统计量
tapply(cont.vars$bwt, INDEX=birthwt$smoke, mean)
tapply(cont.vars$bwt, INDEX=birthwt$smoke, mean)
tapply(cont.vars, INDEX=birthwt$smoke, mean)#显示错误
#3、函数summ():第一个参数必须是一个变量;
# 函数里的统计量是固定的
library(epiDisplay)
summ(cont.vars$bwt,by=birthwt$smoke)
summ(cont.vars,by=birthwt$smoke)#显示错误
#4、函数describeBy():第一个参数可以是数据集也可以是变量;
# 函数里的统计量是固定的
# 与函数describe()相同统计量(峰度和偏度
library(psych)
describeBy(cont.vars,birthwt$smoke)
describeBy(cont.vars$bwt,birthwt$smoke)
#5、函数group_by()和summarise():可指定统计量
library(dplyr)
birthwt%>%
group_by(smoke)%>%
summarise(mean.bwt=mean(bwt),sd.bwt=sd(bwt))
birthwt%>%
group_by(smoke,race)%>%
summarise(mean.bwt=mean(bwt),sd.bwt=sd(bwt))
正态性检验:
install.packages("RVAideMemoire")
library(RVAideMemoire)
byf.shapiro(bwt~smoke,data = birthwt)