R語言基礎統計方法圖文實例講解
更新時間:2021年03月17日 16:03:24 作者:喻解
這篇文章主要介紹了R語言基礎統計方法圖文實例講解,文中圖文合并講解的很透徹,有感興趣的同學可以研究下
tidyr
> tdata <- data.frame(names=rownames(tdata),tdata)行名作為第一列 > gather(tdata,key="Key",value="Value",cyl:disp,mpg)創(chuàng)key列和value列,cyl和disp放在一列中 -號減去不需要轉換的列 > spread(gdata,key="Key",value="Value") 根據value將key打散開 與unite函數對立 separate(df,col=x,into=c("A","B"))將數據框的列分割 unite(x,col="AB",A,B,sep='.')
dplyr
> dplyr::filter(iris,Sepal.Length>7)條件過濾 > dplyr::distinct(rbind(iris[1:10,],iris[1:15,]))去除重復行 > dplyr::slice(iris,10:15)切片 > dplyr::sample_n(iris,10)隨機10行 > dplyr::sample_frac(iris,0.1)按比例隨機選取 > dplyr::arrange(iris,Sepal.Length)排序 dplyr::arrange(iris,desc(Sepal.Length))降序 > select(starwars,height)選取 > summarise(iris,avg=mean(Sepal.Length))
統計函數
%>%鏈式操作符,管道 ctrl+shift+m > iris %>% group_by(Species) > dplyr::group_by(iris,Species) > iris %>% group_by(Species) %>% summarise(avg=mean(Sepal.Width)) %>% arrange(avg) > dplyr::mutate(iris,new= Sepal.Length+Petal.Length)相加總和 > dplyr::left_join(a,b,by="x1") > dplyr::right_join(a,b,by="x1") > dplyr::full_join(a,b,by="x1") > dplyr::semi_join(a,b,by="x1")交集部分 > dplyr::anti_join(a,b,by="x1")補集部分 > intersect(first,second)交集 > dplyr::union_all(first,second)并集 > dplyr::union(first,second)非冗余并集 > setdiff(first,second)補集
heatmap輸入矩陣 lm輸入數據框 plot向量和向量-散點圖,向量和因子-條形圖 cbind,rbind矩陣或數據框 sum,mean,sd,range,median,sort,order向量 main 字符串不能為向量 na.rm true和false axis side參數1到4 fig 包含四個元素向量 > plot(c(1:20),c(seq(1,89,length.out=20)),type="l",lty=1)實線 > plot(c(1:20),c(seq(1,89,length.out=20)),type="l",lty=2)虛線
數學統計
> x <- rnorm(n=100,mean=15,sd=2)生成100個平均數為15方差為2的隨機數 > qqnorm(x) set.seed(666) runif(50)綁定隨機數 dgama(c(1:9),shape=2,rate=1)生成密度gama分布;隨機數
描述性統計
summary() fivenum() Hmisc describe() pastecs stat.desc() basic=T norm=T psych describe() trim=0.1去除最低最高10% > aggregate(Cars93[c("Min.Price","Price","Max.Price"," MPG.city")],by=list(Manufacturer=Cars93$Manufacturer),mean)字符串型 返回一個統計函數 doBy > summaryBy(mpg+hp+wt~am,data=myvars,FUN = mean) psych describe.by(myvars,list(am=mtcars$am))分組統計 describeBy(myvars,list(am=mtcars$am))詳細信息
統計函數 二元類元表
> table(cut(mtcars$mpg,c(seq(10,50,10))))頻數統計 > prop.table(table(mtcars$cyl))頻數占比 > table(Arthritis$Treatment,Arthritis$Improved) > with(data=Arthritis,(table(Treatment,Improved)))省略數據集的名字 > xtabs(~Treatment+Improved,data=Arthritis)根據類別統計頻數 > margin.table(x,1/2)總和 > addmargins(x)將總和添加到原表中 > ftable(y)評估式類元表
獨立性檢驗
原假設:不變 備擇假設:變化 P值越小越能實現 > mytable <- table(Arthritis$Treatment,Arthritis$Improved) > chisq.test(mytable)卡方獨立性檢驗 > fisher.test(mytable)精確獨立檢驗 > mantelhaen.test(mytable) > mytable <- xtabs(~Treatment+Sex+Improved,data=Arthritis) > mantelhaen.test(mytable)
相關性檢驗
> cor(state.x77) > cor(x,y) > cov(state.x77) 偏相關 ggm > pcor(c(1,5,2,3,6),cov(state.x77)) > cor.test(state.x77[,3],state.x77[,5]) psych > corr.test(state.x77) > x <- pcor(c(1,5,2,3,6),cov(state.x77)) > pcor.test(x,3,50) MASS > t.test(Prob~So,data=UScrime)
繪圖函數
散點圖 x、y 直方圖 因子 熱力圖 數據矩陣 象限圖 因子、向量 > plot(women$height~women$weight)關聯圖 > fit <- lm(height~weight,data=women) > plot(fit) S3 par/plot/summary > plot(as.factor(mtcars$cyl),col=c("red","yellow","blue"))
偏度是統計數據分布偏斜方向程度的度量,統計數據分布非對稱程度數字特征、峰度是表征概率密度分布曲線在平均值處峰值高低的特征數
> mystats <- function(x,na.omit=FALSE){ + if(na.omit) + x <- x[!is.na(x)] + m <- mean(x) + n <- length(x) + s <- sd(x) + skew <- sum((x-m^3/s^3))/n + kurt <- sum((x-m^4/s^4))/n-3 + return(c(n=m,mean=m,stdev=s,skew=skew,kurtosis=kurt)) + }
> i=1;while (i<=10){print("Hello,World");i=i+2;} for(i in 1:10){print("Hello,World")} > ifelse(score>60,print("PASS"),print("FAIL")
線性回歸
> fit <- lm(weight~height,data=women) > summary(fit) > coefficients(fit) > confint(fit,level=)置信區(qū)間,默認95% > fitted(fit)擬合模型預測值 源數據-預測值=殘差residuals() > predict(fit,women1)根據結果對新數據進行預測 殘差擬合圖,正態(tài)分布圖,大小位列圖,殘差影響圖 plot(women$height,women$weight) abline擬合曲線 > fit2 <- lm(weight~height+I(height^2),data=women)增加二次項 > lines(women$height,fitted(fit2),col="red") 將點連成線,根據擬合曲線 Pr(>|t|)估計系數為0假設的概率,小于0.05 Residual standard error殘差越小越好 Multiple R-squared擬合值越大越好,解釋數據量 F-statistic模型是否顯著,越小越好
AIC比較回歸值擬合度結果 MASS stepAIC逐步回歸法 leaps regsubsets全子集回歸法
> par(mfrow=c(2,2)) plot四幅圖顯示在同個畫面 抽樣驗證法 500個數據進行回歸分析,predict對剩下500個預測,比較殘差值
單因素方差分析
> library(multcomp) > attach(cholesterol) > table(trt) > aggregate(response,by=list(trt),FUN=mean) 分組統計平均值查看效果最好因子 > fit <- aov(response~ trt,data=cholesterol) 方差分析 > summary(fit) 看統計結果,方差結果看F值 越大組間差異越顯著、P值衡量F值越小越可靠
協方差
> attach(litter) > aggregate(weight,by=list(dose),FUN=mean) > fit <- aov(weight~gesttime+dose,data=litter) > summary(fit)
雙因素方差分析
> attach(ToothGrowth) > xtabs(~supp+dose)統計頻率 > aggregate(len,by=list(supp,dose),FUN=mean)劑量越小兩者差別越明顯 > ToothGrowth$dose <- factor(ToothGrowth$dose) > fit <- aov(len ~ supp*dose,data=ToothGrowth) > summary(fit)
HH
> interaction.plot(dose,supp,len,type="b", col=c("red","blue"),pch=c(16,18), main = "Interaction between Dose and Supplement Type")
多元方差分析
> library(MASS) > attach(UScereal) > shelf <- factor(shelf) > aggregate(cbind(calories,fat,sugars),by=list(shelf),FUN=mean) > summary.aov(fit)每組測量值不同,差異結果顯著
功效分析
> pwr.f2.test(u=3,sig.level=0.05,power=0.9,f2=0.0769)假設顯著性水平為0.05,在90%置信水平下至少需要184個樣本 pwr.anova.test(k=2,f=0.25,sig.level=0.05,power=0.9) 2組效率為0.25顯著性水平為0.05,功效水平為90,結果為86*2
> data(breslow.dat,package = "robust") > summary(breslow.dat) > attach(breslow.dat) fit <- glm(sumY~Base + Trt +Age,data=breslow.dat,family=poisson(link="log")) 廣義線性模型擬合泊松回歸 響應變量
邏輯回歸
> data(Affairs,package="AER") > summary(Affairs) > table(Affairs$affairs) > prop.table(table(Affairs$affairs)) > prop.table(table(Affairs$gender)) > Affairs$ynaffair[Affairs$affairs>0] <- 1 > Affairs$ynaffair[Affairs$affairs==0] <- 0 > Affairs$ynaffair <- factor(Affairs$ynaffair,levels=c(0,1),labels=c("No","Yes")) > table(Affairs$ynaffair) > attach(Affairs ) > fit <- glm(ynaffair~gender+age+yearsmarried+children+religiousness+education+occupation+rating,data=Affairs,family=binomial()) > summary(fit) > fit1 <- glm(ynaffair~age+yearsmarried+religiousness+rating,data=Affairs,family=binomial()) > summary(fit1) > anova(fit,fit1,test="Chisq")
主成分分析
> library(psych) > fa.parallel(USJudgeRatings,fa="pc",n.iter=100)直線與X符號生成值大于一和100次模擬的平行分析 CPU > pc <- principal(USJudgeRatings,nfactors=1,rotate="none",scores=FALSE)/scores=T pc1包含成分整合,觀測變量與主成分的相關系數,h2指成分公因子的方差,主成分對每個變量的方差解釋度,u2指方差無法被主成分解釋的比例,SSloadings特定主成分相關聯的標準化后的方差值,proportion var每個主成分對相關值的解釋程度
因子分析
> library(psych) > options(digits=2) > covariances <- ability.cov$cov > correlations <- cov2cor(covariances) > fa.parallel(correlations,fa="both",n.obs=112,n.iter=100) > fa.varimax <- fa(correlations,nfactors=2,rotate="varimax",fm="pa") > fa.promax <- fa(correlations,nfactors=2,rotate="promax",fm="pa") factor.plot(fa.promax,labels=rownames(fa.promax$loadings)) fa.diagram(fa.varimax,simple=FALSE) fa<-fa(correlations,nfactors=2,rotate="none",fm="pa",score=TRUE) fa$weight
library(arules) data(Groceries) > fit <- apriori(Groceries,parameter=list(support=0.01,confidence=0.5)) > inspect(fit)
到此這篇關于R語言基礎統計方法圖文實例講解的文章就介紹到這了,更多相關R語言基礎統計方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!