Presentation is loading. Please wait.

Presentation is loading. Please wait.

R軟體基本使用 R軟體安裝與基本使用 R基本運算和變數種類 R的版面配置與繪圖功能 4 2 3 1 資料輸出入與資料處理.

Similar presentations


Presentation on theme: "R軟體基本使用 R軟體安裝與基本使用 R基本運算和變數種類 R的版面配置與繪圖功能 4 2 3 1 資料輸出入與資料處理."— Presentation transcript:

1 R軟體基本使用 R軟體安裝與基本使用 R基本運算和變數種類 R的版面配置與繪圖功能 4 2 3 1 資料輸出入與資料處理

2 R軟體簡介、安裝R、直接執行R指令、撰寫R程式及自訂函數、使用輸出入資料檔、程式執行結果的記錄檔、使用內建資料檔

3 R軟體簡介 R軟體包含資料處理、統計分析、科學運算、圖形功能及資料探勘等功能。
R軟體最早是由奧克蘭大學的Robert Gentleman & Ross Ihaka兩位學者於1995年仿S語言(1976貝爾實驗室研發)而發展出來的統計軟體。目前R軟體則是開放原始碼,陸續還會有許多套件(packages)的新增與更新,不斷地擴充R軟體的功能。 R軟體的主要組成包括:R核心程式與基本套件、R直譯器、眾多套件與函數、GUI。

4 下載R軟體 http://www.r-project.org

5 範例一:直接執行R指令

6 help指令或?查詢rnorm函數

7 plot指令畫出的X-Y散佈圖

8 範例二:撰寫R程式

9 執行程式檔

10 R程式撰寫說明 > 字號為輸入指令的提示符號,一行多個運算式可以;號隔開,一個運算式可分成多行 # 字號之後為註解,程式不會執行
+ 字號表示尚未輸入完成,可按Esc離開 ↑鍵可自動重複上一個指令 Assign符號可為<- 或=號,以()括住指令直接顯示資料 變數或函數名稱可以是英數字加底線或句點,第一個字必須是英文,有大小寫的差異 NA表示missing value 、NaN表示not a number 、NULL表示empty object 檔案路徑可寫成sink("c:/R/sink.log")或sink("c:\\R\\sink.log")

11 撰寫自訂函數mybmi mybmi<-function(h,w) { bmi=w/(h/100)^2 return(bmi) }
程式檔名為myfun.R

12 要用時直接載入執行

13 使用自訂函數mybmi

14 範例三:使用輸出入資料檔 以read.table指令讀入此檔,放在資料框架變數mydata

15 自訂函數mybmi執行結果

16 將數個變數組成資料框架變數

17 輸出成文字資料檔 以write.table指令將資料框架變數all 輸出到檔案

18 範例四:記錄程式執行的結果 mydata=read.table("c:/r/input.txt", header= TRUE)
#設定記錄結果的檔名 sink("c:/R/sink.log") summary(mydata) summary(mydata$weight) summary(lm(mydata$height~ mydata$weight)) #以sink()結束記錄動作 sink()

19 記事本開啟的結果檔

20 範例五:使用內建資料檔

21 iris的基本敘述統計

22 練習:乳腺癌醫學診斷應用 本範例檔wdbc.txt的乳腺癌(Breast Cancer Diagnostic)的診斷資料,取自美國加州大學歐文分校的機械學習資料庫 Wisconsin大學臨床研究中心於1995年蒐集569例乳腺癌症的病患實際診斷資料,診斷的方式是對於可疑的乳腺腫塊使用細針穿刺的技術 (Fine Needle Aspirate, FNA)蒐集數位化圖像並加以計算

23 乳腺癌醫學診斷欄位說明 wdbc.txt的欄位計有32項,分別是 1. 識別號碼(ID number):識別號碼
2. 診斷結果(Diagnosis):惡性(M = malignant)、良性(B = benign) 3-32. 這30項資料是計算每一個細胞核的真實資料測量值,包含以下的內容:半徑(radius)、紋理(texture)周長(perimeter)、範圍(area)、平滑度(smoothness)、緊密度(compactness)、凹陷部分的程度(concavity)、凹陷部分的數量(concave points) 、對稱度(symmetry) 、碎型維度(fractal dimension)

24 wdbc=read.table("d:\\stella\\R\\wdbc.txt",header=T,sep=",")
#redirect screen output to file sink("d:\\stella\\R\\out.txt") summary(wdbc) # descriptive statistics head(wdbc) # browse 6 records attach(wdbc) # do not need wdbc$c1 # cat is printing function, \t \n are tab newline cat("c1 mean=",round(mean(c1),2),"\tc1 std=",round(sd(c1),2),"\n") cat("c2 mean=",round(mean(c2),2),"\tc2 std=",round(sd(c2),2),"\n") sink()

25 R軟體基本運算、R的資料屬性、向量變數、陣列變數、矩陣變數、因子變數、串列變數、資料框架變數、時間數列變數

26 greater than or equal to
算術、比較、邏輯運算子 Arithmetic算術 Comparison比較 Logical邏輯 + addition < lesser than !x NOT - subtraction > greater than x&y AND * multiplication <= lesser than or equal to x&&y AND條件 / division >= greater than or equal to x|y OR ^ 或** power == equal x||y OR條件 %% modulo != different xor(x,y) exclusive OR %/% integer division >a=c(0,1,0,1) >b=c(0,0,1,1)   向量邏輯運算 >a&b或 a|b 

27 R軟體字串和有序數列運算

28 R軟體基本向量運算(vector)

29 R軟體基本統計運算

30 R的資料屬性 Logical—邏輯TRUE(T) 、 FALSE (F) Integer—整數 Double—又稱real或 numeric
Complex—複數 3+2i或寫成 x= complex( real=3,imaginary=2) Character—文字字串(character或string) name=“John” Raw—二進位資料

31 向量變數(Vector) 可視為一個集合或有序(ordered)物件,元素屬性需相同
從1開始的指標系統,如x[3]指向x向量的第3個元素,x= x[-5]可刪除x向量的第5個元素 向量變數常用的函數: is.vector(x)、 c()、length、dim、names 、matrix(x,r,c) 將向量x轉為r列c行的矩陣

32 向量變數常用的函數

33 陣列變數(Array) 陣列變數可視為多維度版本的向量變數,元素屬性需相同,如x[i,j,k]
陣列變數常用的函數: rbind、 cbind、array函數是以逐欄方式放資料、 length、ncol、nrow 、column、 row、 dim、 colnames、 rownames、 dimnames 、aperm轉置

34 陣列變數常用的函數

35 矩陣變數(Matrix) 矩陣變數是陣列變數的2維特例,例如x[i,j] 矩陣變數常用的函數: t(x) : 轉置矩陣
as.matrix(x) : 將框架變數轉成矩陣型態 %*% : 矩陣相乘或矩陣和向量相乘(加減+ -) diag(x) : 對角線 diagonal det(x) : 行列式值 determinant solve(x) : 反矩陣 inverse matrix eigen(x) :特徵值與特徵向量eigenvalue matrix(1:20,nrow=5,ncol=4,byrow=TRUE) cbind、 rbind、 colnames、 rownames 、 dim

36 矩陣變數常用的函數 A[2, ] A[ ,1] A[1,2]

37 因子變數(Factor) 因子變數可用來儲存分類變數,很像是文字向量,若因子變數各分類間有特定順序關係,則稱為有序(ordered)因子變數,可以用來比較大小 因子變數常用的函數: factor、as.factor:建立因子變數 ordered、as.ordered:建立有序因子變數 levels:查詢或設定分類資料

38 因子變數常用的函數

39 串列變數(List) 串列變數的元素可以是不同長度、不同變數種類,可以是數值、文字、向量、矩陣、陣列、因子、資料框架,甚至是另一個串列
可用數字指標系統,也可使用串列變數$名稱指標來找尋個別元素 可利用names或attributes函數查看串列變數的名稱指標,很多函數的傳回值都是用串列變數 list(元素名稱1=元素值1,元素名稱2=元素值2,元素名稱3=元素值3,…)

40 串列變數常用的函數

41 資料框架變數(Data-Frame) 資料框架變數是用來儲存一個資料檔所有的變數與觀察值,各個行向量長度必須相等,同一個行向量的需為相同屬性,類似Excel的工作表 資料框架變數常用的函數: data.frame() 、edit : 建立資料框架變數 edit、fix : 編輯資料框架變數 names與colnames : 設定或查詢直行名稱 rownames與row.names: 設定或查詢橫列名稱 X=read.table(“data.txt”) : 讀入外部資料檔

42 讀入與使用資料框架變數

43 使用資料框架變數的註解 mydata=read.table(file=“c:\\r\\data.txt”, col.names=c(“name”,”age”,”sex”)) 檔案中有變數名稱,加上header=T,檔案中沒有變數名稱,也沒有用col.names設定,則預設為V1,V2… mydata[2]、mydata[” V2”]: 傳回值是框架變數 mydata$V2、mydata[,2]、mydata[,”V2”] : 傳回值是向量

44 寫出與編輯資料框架變數

45 時間數列變數(Time-Series) ts是處理時間數列資料變數的函數,時間數列的迴歸函數,如ar或arima函數採用ts變數
基本語法 ts(x,start,end,frequency), x可以是向量、陣列或矩陣,end可省略,start=c(t1,t2),t1是第一個時間單位的起點,t2是第二個時間單位的起點,如start=c(2012,3),可搭配freq=4季 或12 月或365天

46 時間數列變數的函數

47 練習:小迴圈 iris 4個數值欄位的平均和標準差 wdbc 30個數值欄位的平均和標準差
輸出顯示: cat(字串或變數,字串或變數…,file= “ “,sep=“ “,append=FALSE) for (i in 1:4) { ……..iris[, i] }

48 使用迴圈 wdbc=read.table("d:\\stella\\R\\wdbc.txt", header=T,sep=",")
sink("d:\\stella\\R\\out.txt") attach(wdbc) # do not need wdbc$c1 for (i in 3:32) { cat("c",i-2,"mean=",round(mean(wdbc[,i]),2), "\tc1 std=",round(sd(wdbc[ ,i]),2),"\n") } sink()

49 三.資料輸出入與資料處理 文字資料的輸入輸出、R套件的使用、讀取Excel資料檔、存取R軟體的二進位資料檔、重新編碼、資料排序、資料合併、資料篩選、字串處理、資料格式轉換

50 資料輸入檔案格式 read.table: 空格分隔的格式檔案 read.csv: 逗號分隔的格式檔案
read.delim: TAB鍵分隔的格式檔案 read.fwf: 固定寬度的格式檔案

51 資料輸入輸出範例

52 R軟體已安裝的套件

53 或直接 >install.packages(“car”)
安裝R套件car 或直接 >install.packages(“car”)

54 載入R套件car *只要安裝1次,每次要用時載入即可 >install.packages(“car”)
>library(car) *查詢檢視 >library()檢視已安裝的套件 >search()檢視已載入的套件

55 讀取Excel檔(readxl套件)

56 存取Excel資料檔(需xlsx套件)

57 存取R軟體的二進位資料檔 R軟體本身提供二進位的資料檔格式(.rda或Rdata) ,方便使用者儲存操作過程中的物件,包含自訂函數、變數等
getwd(“d:\\stella”) 目前工作區目錄 setwd(“d:\\stella”) 設定工作區目錄 ls() 顯示工作區所有物件 rm(list=ls()) 清除工作區所有物件 save(x,y,myfunc,file=“c:/r/mydata.rda”) save.image(“c:/r/alldata.rda”) load(“c:/r/mydata.rda”)

58 重新編碼的方法 使用邏輯判斷式:TRUE為1,FALSE為0
使用ifelse函數:ifelse(邏輯判斷式,TRUE傳回值,FALSE傳回值) 使用cut()函數 使用recode()函數

59 重新編碼(邏輯判斷式和ifelse函數)
ifelse(邏輯判斷式,TRUE傳回值,FALSE傳回值) >newgroup=ifelse(income>=60000,”RICH”,”POOR”)

60 cut()函數 cut(x,breaks,labels,right=T, include.lowest=F)
breaks為切割點資訊,若為整數k表分割成均等的k組 labels為切割後的各組名稱,若無此項則傳回數字向量 include.lowest=F表示不含各區間的最小值 right=T表示各區間左端open右端closed

61 car套件的recode函數 設定重新編碼規則的字串,以分號分隔編碼 規則,規定如下: 舊碼=新碼 例如: 0=NA 舊碼向量=新碼
例如: c(7,8,9)=“high” start:end=新碼 例如: 7:9=‘C’或lo:10=1或11:hi=2 else=新碼 例如: else=NA

62 重新編碼(cut函數和recode函數)

63 資料的排序 sort(X,decreasing=FALSE): 從小排到大或從大排到小 rank(X): 各元素的排序等級
order(X): 先將元素由小到大排好,再傳回其在原向量的數字指標 rev(X): 將整個向量倒過來排 整個資料檔排序: >iris[order(Sepal.Length),]

64 資料的排序

65 資料的合併 垂直合併(rbind函數): 兩個框架變數具相同的欄位,但不含相同橫列資料
水平合併(merge函數):兩個框架變數具有大致相同的橫列資料,但除了主鍵以外具有不同的欄位資料 merge(x,y,by=“id”)顯示x y交集的資料 merge(x,y,by=“id”, all=T)顯示x y聯集的資料 merge(x,y,by=“id”,all.x=T)顯示x各筆資料 merge(x,y,by=“id”,all.y=T)顯示y各筆資料

66 資料的合併

67 資料篩選的方法 使用split函數篩選資料 使用指標篩選資料 使用sample函數隨機篩選資料 使用邏輯值篩選資料
使用subset函數篩選資料

68 使用split函數篩選資料

69 使用指標篩選資料 列的篩選 iris2=iris[10:12,] iris2=iris[-(10:12),] 欄的篩選
iris2=iris[,5]或iris[,”Species”] iris2=iris[,-5]或iris[,1:4] 欄列的篩選 iris2=iris[51:100,c(1,2,5)] iris2=iris[iris$Species==“setosa,]

70 sample函數和邏輯值篩選資料 *隨機取樣 抽出不放回 *間隔取樣 每10筆取1
>babies[ seq(1,nrow(babies),10), ] or >babies[as.numeric(rownames(babies) )%% 10==0,]

71 使用subset函數篩選資料

72 字串處理函數 字串黏貼: paste(…, sep=“ “)
訊息顯示: cat(字串或變數,字串或變數…,file= “ “,sep=“ “,append=FALSE) 取子字串: substr(x,start,stop) 取代子字串: sub(old,new,x) 取代所有子字串: gsub(old,new,x) 字串切割: strsplit(x, “ “) 找尋子字串:grep(子字串,x,ignore.case=FALSE)

73 字串處理函數範例

74 正規表示式擷取關鍵字 grep(pattern, x, ignore=F) ^表子字串出現在x最前面 $表子字串出現在x最前面
A-F 包含A B C D EF [ABC]將特定規則群集起來 A或B或C [^ABC]A或B或C以外 ?regex查詢

75 擷取關鍵字範例

76 資料格式轉換(long-wide format)
#stack and unstack (chicken=read.table("d:\\stella\\R\\test.csv",sep=",",header=T)) chicken=chicken[,-1] (chicken2=stack(chicken)) #names(chicken2)=c("weight","feed") (chicken3=unstack(chicken2)) #reshape long and wide format chicken=read.table("d:\\stella\\R\\test.csv",sep=",",header=T) chicklong=reshape(chicken,direction="long",varying=list(c("Ration1","Ration2","Ration3")),v.names="ration", idvar="id") chicklong chickwide=reshape(chicklong,direction="wide", idvar="id") chickwide

77 stack函數

78 unstack函數

79 reshape函數

80 綜合應用:水平合併或取聯集

81 綜合應用: 水平合併或取聯集 # method 1 : horizontal merge
test=read.table("D:\\stella\\R\\input3.txt", header=T) t0=test[,1:4] t1=test[grep("tea",test$item1,ignore.case=FALSE),c(1,5)] t2=test[grep("tea",test$item2,ignore.case=FALSE),c(1,6)] tt=merge(t1,t2,by="id",all=T) (hall=merge(t0,tt,by="id",all.tt=T)) #method 2 : horizontal merge l1=grep("tea",test[,5]) l2=grep("tea",test[,6]) t=test[union(l1,l2) ,] t[order(t$id),]

82 練習:有遺漏值的babies資料檔 資料的筆數計有1236筆,共有7個欄位(bwt:嬰兒體重, gestation:懷孕日數, parity:胎序,懷孕過幾胎, age:母親年齡, height :母親身高, weight :母親體重, smoke:母親抽煙與否,1表抽煙0表不抽煙) summary(babies) nrow(babies) mean(babies$gestation,rm.na=T) babies[babies$age<18 & is.na(babies$age),] babies=na.exclude(babies)

83 練習:wdbc分組平均數 wdbc=read.table("d:\\stella\\wdbc.txt", header=T,sep=",")
attach(wdbc) for (i in 3:32) { cat(paste(“c”,i-2,sep=“”),“total mean=”, round(mean(wdbc[,i]),4),"\n") cat(“B mean=”, round(mean(wdbc[diagnosis=="B",i]),4),"\n") cat(“M mean=”, round(mean(wdbc[diagnosis=="M",i]),4),"\n") }

84 四. R的版面配置與繪圖功能 圖形的版面配置、圖形設定參數、散佈圖、函數曲線、矩陣圖、條件散佈圖、常態機率圖、直方圖、長條圖、盒狀圖、圓餅圖、3D繪圖、附加圖形應用、進階3D繪圖、程式迴圈繪圖

85 圖形區域的版面配置 R最具特色的功能之一就是繪圖功能,一般是一張紙畫一個圖形,但R可以將多張圖形放在同一張紙,但事先最好先儲存一張圖的原始設定,如oldpar=par(),之後再以指令par(oldpar)恢復原設定一張紙一個圖,方式包括以下三種: par函數搭配mfrow或參數mfcol參數: 適合規則形狀的多張圖形分布 layout函數:適合不規則的多張圖形分布 par函數搭配fig參數: 適合不規則的多張圖形分布

86 par()函數搭配mfrow參數 適合規則形狀的多張圖形分布,例如
par(mai=c(0.5,0.5,0.5,0.5),mfrow=c(3,2)) mai設定紙張邊緣(英吋) 依序是底部、左邊、頂端、右邊,mfcol是逐欄,mfrow是逐列排列 將babies.txt依年齡分為6組(~20、20-25、25-30、30-35、35-40、40~)畫6個height和weight的散佈圖

87 多張規則圖形的程式碼 babies=read.table(“d:/R/babies.txt”,header=T)
grp1=subset(babies,age<20) grp2=subset(babies,age>=20 & age<25) grp3=subset(babies,age>=25 & age<30) grp4=subset(babies,age>=30 & age<35) grp5=subset(babies,age>=35 & age<40) grp6=subset(babies,age>=40) #oldpar=par() par(mai=c(0.5,0.5,0.5,0.5),mfrow=c(3,2)) #by rows plot(grp1[,"height"],grp1[,"weight"]) #plot(x,y) x y are vectors plot(grp2[,"height"],grp2[,"weight"]) plot(grp3[,"height"],grp3[,"weight"]) plot(grp4[,"height"],grp4[,"weight"]) plot(grp5[,5],grp5[,6]) plot(grp6$height,grp6$weight) #par(oldpar)

88 6個規則圖形的散佈圖

89 layout函數:不規則的多個圖形 1 2 3 2 1 3 layout(M,widths,heights)
M是圖形分佈的矩陣,widths、heights各是設定M矩陣長、寬的比例,其基準點是左下角 上圖的指令為2x2矩陣layout(matrix(c(1,1,2,3),2,2, byrow=T)) 下圖的指令為2x2矩陣 layout(matrix(c(2,0,1,3),2,2, byrow=T), widths=c(3,1), heights=c(1,3)) 1 2 3 2 1 3

90 layout函數的程式碼 attach(iris)
layout(matrix(c(2,0,1,3),2,2, byrow=T), widths=c(2,1), heights=c(1,2)) plot(Sepal.Length,Sepal.Width,main="Sepal Length-Width Scatter Graph") hist(Sepal.Length,main="Sepal Length Histogram Graph") hist(Sepal.Width,main="Sepal Width Histogram Graph")

91 layout函數的多個圖形

92 par函數搭配fig參數 par(fig=c(x1,x2,y1,y2))
par(fig=c(0,0.8,0.7,1)) 大約是圖2的版面位置, 左下角座標(x1,y1)是(0,0.7) ,右上角座標(x2,y2)則是(0.8,1) (0,1) (1,1) 2 1 3 (1,0) (0,0)

93 par函數搭配fig參數程式碼 attach(iris) par(fig=c(0,0.6,0,0.6),new=TRUE)
plot(Sepal.Length,Sepal.Width,main="Sepal Length-Width Scatter Graph") par(fig=c(0,0.6,0.6,1),new=TRUE) hist(Sepal.Length,main="Sepal Length Histogram Graph") par(fig=c(0.6,1,0,0.6),new=TRUE) hist(Sepal.Width,main="Sepal Width Histogram Graph")

94 par函數搭配fig參數多個圖形

95 圖形基本設定參數 col=k : 設定color,可用在col.axis、col.lab、col.main、col.sub,設定座標軸、X與Y軸、主標題、附標題的顏色,可以color()查到顏色名稱 lty=k : line type , k=1為實線 lwd=k : line width , k為標準線寬的倍數 pch=k或”圖點符號”,預設為圓點, k=0~20 font=k :設定字體,1一般字體、2粗體、3斜體、4粗斜體,可用在font.axis、font.lab、font.main、font.sub cex=k : 設定字型的倍數(可為小數),可用在cex.axis、cex.lab、cex.main、cex.sub

96 plot散佈圖、長條圖、盒狀圖 >plot(Species) >plot(iris)或 pairs(iris)
>plot(Sepal.Length,Sepal.Width) >plot(Species,Sepal.Length) >plot(iris)或 pairs(iris) >plot(~Sepal.Length+ Petal.Length+Petal.Width) >plot(Sepal.Length)

97 curve 函數曲線 curve(x^2-4*x+3,-4,4,lty=2,add=T) curve(sin(x),-4,4)

98 pair矩陣圖 >pair(iris)

99 coplot條件散佈圖(加 ,rows=1) > coplot(Sepal.Length~Petal.Length | Species)

100 常態機率圖qqnorm qqline、qqplot
qqplot(Sepal.Length,Sepal.Width) qqnorm(Sepal.Length)+ qqline(Sepal.Length)最佳線

101 直方圖hist hist(Sepal.Length,breaks=4:8) hist(Sepal.Length,nclass=8)

102 bar plot長條圖 cancers=c(11,16,17,6,12)
labels=c("乳癌","支氣管癌","結腸癌","卵巢癌","胃癌") barplot(cancers) barplot(cancers,names=labels) barplot(cancers,names=labels,horiz=T) barplot(cancers,names=labels,col=c(1,2,3,4,5)) barplot(cancers,names=labels,col=c(1,2,3,4,5), density=10) barplot(cancers,names=labels,col=c(1,2,3,4,5), density=40)

103 barplot長條圖

104 boxplot盒狀圖 boxplot(iris[,1],xlab="SLen",main="(F1)")
boxplot(iris[,1:4],main="(F2)") boxplot(iris[,1:4],main="(F3)",names=c("Slen","Swid","Plen","Pwid")) boxplot(iris[,1:4],main="(F4)",horizontal=T) boxplot(iris[,4]~iris[,5],main="(F5)",xlab="flower class",ylab="Slen") boxplot(Sepal.Length~Species,data=iris,main="(F6)",xlab="flower class",ylab="Slen“ ,col=c(2,3,4))

105 boxplot盒狀圖

106 Pie圓餅圖 sales=c(0.12,0.3,0.26,0.16,0.04, 0.12) snames=c("電腦","廚具","家電","傢俱","其他","服飾") pie(sales, label= snames)

107 3D繪圖contour 、 image 、persp
contour(x,y,z):畫出地圖效果的等高線圖 image(x,y,z):類似於contour,但可畫出色彩 persp(x,y,z,theta,phi,box=TRUE):畫出真正的三度空間透視圖,theta控制圖形上下旋轉角度,phi控制圖形左右旋轉角度,box=TRUE則不畫出框線 >demo(graphics) #展示繪圖功能 等高線圖>filled.contour(volcano,color=terrain.colors,plot.axes=contour(volcano,add=TRUE))

108 3D繪圖contour 、 image 、persp
x=seq(-3,3,0.1) y=x f=function(x,y){(1/(2*pi))*exp(-0.5*(x^2+y^2))} z=outer(x,y,f) #外積函數outer par(mfcol=c(2,2)) contour(x,y,z) image(x,y,z) persp(x,y,z) persp(x,y,z,theta=30,phi=30,box=F, main= "persp theta=30 phi=30")

109 3D繪圖contour 、 image 、persp

110 繪圖函數的共用輔助參數 main=“” 、 sub=“” 、xlab=“” 、ylab=“”
xlim=c(xmin,xmax) 、 ylim=c(0,30) add=TRUE #覆蓋前一張圖 axes=FALSE #不畫出座標軸 xaxt=“n” yaxt=“n” #不畫出座標軸格線 right=FALSE #即右邊為開放區間 < log=“x”、 log=“y”、 log=“xy” type=“p”:points only 、type=“l”:lines only type=“b”:points and lines、 type=“o”:overlap type=“s”:steps 、type=“h”:height

111 plot圖點樣式 x=rnorm(10,0,1) >plot(x,type=“p”) >plot(x,type=“l”)
>plot(x,type=“b”) >plot(x,type=“o”) >plot(x,type=“h”) >plot(x,type=“s”)

112 附加圖形:points、lines、text
height=sample(150:190, 30,replace=TRUE) score=sample(c(60:100), 30,replace=TRUE) xp=c(160,165,170,175) yp=c(80,90,80,90) plot(height,score) points(xp,yp,col=2, pch=19) lines(xp,yp,col=3) text(xp,yp+5,col=4, label=c("P1","P2","P3","P4"))

113 附加圖形:legend、title、axis
age=sample(20:60,100, replace=TRUE) sex=sample(c("M","F"),100,replace=TRUE) race=sample(c("WHITE","YELLOW","BLACK"),100,replace=TRUE) data=data.frame(age,sex,race) barplot(table(race),col= 4:6) table(race)

114 附加圖形:legend、title、axis
table(sex,race) F M barplot(table(sex,race), col =c(“pink”,“blue”), axes= FALSE, beside=TRUE) legend(0.5,40,c("Female","Male"),col=c("pink","blue"),pch=15) title(main="Race and Sex Bar Chart",sub="in1988") axis(2,las=2) 1底部 2左邊 las=2水平數字

115 也可在既有圖形加入add=T boxplot(age~race, main="Age by Race", col="yellow",boxwex=0.3) boxplot(age[sex== "M"]~race[sex=="M"],col="blue",boxwex=0.1,at= c(1.3,2.3,3.3), add=TRUE, axes=F)

116 自訂座標軸及互動式圖形 attach(iris)
plot(Sepal.Length,Petal.Length,xaxt="n",yaxt="n",xlim=c(4,8)) axis(side=1,at=seq(4,8,by=0.5)) axis(side=2,las=2) abline(v=7,col="red") identify(Sepal.Length,Petal.Length) 按右鍵的停止功能結束

117 附加圖形應用:points、 legend
plot(Sepal.Length[Species=="setosa"],Petal.Length[Species=="setosa"], pch=1 ,col="black", xlim=c(4,8), ylim= c(0,8), main="classified scatter plot", xlab= "SLen", ylab= "PLen") points(Sepal.Length[Species=="virginica"],Petal.Length[Species=="virginica"],pch=3,col="green") points(Sepal.Length[Species=="versicolor"],Petal.Length[Species=="versicolor"],pch=2,col="red") legend(4,8,legend=c("setosa","versicolor","virginica"),col=c(1,2,3),pch=c(1,2,3))

118 附加圖形應用iris

119 Taiwan map

120 Taiwan map library(maps) x=world.cities
taiwan=x[x$country.etc=="Taiwan", ] taiwan map("world",xlim=c(120,122),ylim=c(21.2,25.5),mar=c(1,1,1,1)) taiwan.city=taiwan[taiwan$name %in% c("Taipei", "Taoyuan","Taichung","Tainan","Kaohsiung"), ] map.cities(taiwan.city,capital=1) map.cities(taiwan.city,label=TRUE) mpop=taiwan[taiwan$pop > ,] symbols(mpop$long,mpop$lat,circle=mpop$pop,inches=0.2,fg=2,lwd=2,add=TRUE)

121 Scatterplot3d之一 library("scatterplot3d") scatterplot3d(iris[,1:3])
scatterplot3d(iris[,1:3],angle=55, main="3D Scatter Plot", xlab = "Sepal Length (cm)", ylab = "Sepal Width (cm)", zlab = "Petal Length (cm)") scatterplot3d(iris[,1:3], pch = 16, color="steelblue")

122 Scatterplot3d之一

123 Scatterplot3d之二 #Change point shapes and colors by groups
shapes = c(16, 17, 18) shapes <- shapes[as.numeric(iris$Species)] scatterplot3d(iris[,1:3], pch = shapes) colors <- c("#999999", "#E69F00", "#56B4E9") colors <- colors[as.numeric(iris$Species)] scatterplot3d(iris[,1:3], pch = 16, color=colors)

124 Scatterplot3d之二

125 Scatterplot3d之三 #Remove box and add bars
scatterplot3d(iris[,1:3], pch = 16, color = colors, grid=TRUE, box=FALSE) scatterplot3d(iris[,1:3], pch = 16, type="h", color=colors)

126 Scatterplot3d之三

127 Scatterplot3d之四 # Custom shapes/colors legends or points label
s3d <- scatterplot3d(iris[,1:3], pch = shapes, color=colors) legend("bottom", legend = levels(iris$Species), col = c("#999999", "#E69F00", "#56B4E9"), pch = c(16, 17, 18), inset = -0.25, xpd = TRUE, horiz = TRUE, cex=0.5) # inset:distance between plot and legend # xpd:enable legend outside plot scatterplot3d(iris[,1:3], pch = 16, color=colors) text(s3d$xyz.convert(iris[, 1:3]), labels = rownames(iris), cex= 0.7, col = "steelblue")

128 Scatterplot3d之四

129 Scatterplot3d之五 oldpar=par() par(mfcol=c(1,2))
s3d=scatterplot3d(Nuts, Eggs, Milk, col.axis="blue", col.grid="lightblue", main="scatterplot3d - 1", pch=16,color=as.numeric(Country)) text(s3d$xyz.convert(data[,c(9,4,5)]), labels = Country, cex= 0.6, col = "steelblue") t3d=scatterplot3d(RedMeat, WhiteMeat, Fish,col.axis="blue", col.grid="lightblue", main="scatterplot3d - 2", pch=16,color=as.numeric(Country)) text(t3d$xyz.convert(data[,c(2, 3,6)]), labels = Country, cex= 0.6, col = "steelblue") par(oldpar)

130 Scatterplot3d之五

131 plot3D套組說明 scatter3D(x, y, z, ..., colvar = z, col = NULL, add = FALSE) text3D(x, y, z, labels, colvar = NULL, add = FALSE) points3D(x, y, z, ...) #scatter3D(…, type =“p”) lines3D(x, y, z, ...) #scatter3D(…, type =“l”) scatter2D(x, y, colvar = NULL, col = NULL, add = FALSE) text2D(x, y, labels, colvar = NULL, col = NULL, add = FALSE)

132 plot3D套組說明 x, y, z: vectors of point coordinates
colvar: a variable used for coloring by z ,unless colvar = NULL col: color palette used for coloring colvar variable labels: the text to be written add: logical. If TRUE, then the points will be added to the current plot. If FALSE a new plot is started …: additional persp arguments including xlim, ylim, zlim, xlab, ylab, zlab, main, sub, r, d, scale, expand, box, axes, nticks, tictype.

133 scatter3D之一 library(plot3D) attach(iris)
x=Sepal.Length;y=Petal.Length;z=Sepal.Width oldpar=par() par(mfcol=c(1,2)) #By default, the points are colored automatically using the variable Z scatter3D(x,y,z, clab = c("Sepal", "Width (cm)")) scatter3D(x,y,z, colvar = NULL, col = "blue", pch = 19, cex = 0.5) par(oldpar)

134 scatter3D之一

135 scatter3D之二 #title and axis labels
scatter3D(x, y, z, phi = 0, bty = "g", pch = 20, cex = 2, ticktype = "detailed", main = "Iris data", xlab = "Sepal.Length",ylab ="Petal.Length", zlab = "Sepal.Width") # Create a scatter plot and text scatter3D(x, y, z, phi = 0, bty = "g", pch = 20, cex = 0.5) text3D(x, y, z, labels = rownames(iris),add = TRUE, colkey = FALSE, cex = 0.5)

136 scatter3D之二

137 scatter3D之三 data=read.table("d:\\stella\\R\\protein.txt", header=T)
attach(data) scatter3D(Nuts,Fr.Veg,Fish,phi = 0, bty = "g",colvar = NULL, col = "red",pch = 16, cex = 0.5, main = "6 variables (red & blue)", xlab = "Nuts & Eggs",ylab ="Fr.Veg & WhiteMeat", zlab = "Fish & ReaMeat") text3D(Nuts,Fr.Veg,Fish,labels =rownames(data),add = TRUE, colkey = FALSE, cex = 0.5) scatter3D(Eggs,WhiteMeat,RedMeat,colvar = NULL, col = "blue",pch = 19, cex = 0.5,add=T) text3D(Eggs, WhiteMeat, RedMeat,labels = rownames(data),add=TRUE,colkey = FALSE, cex = 0.5)

138 scatter3D之三

139 scatter3D之四 # 4D and choose suitable ranges
with(USArrests, text3D(Murder, Assault, Rape, labels = rownames(USArrests), colvar = UrbanPop, col = gg.col(100), theta = 60, phi = 20, xlab = "Murder", ylab = "Assault", zlab = "Rape", main = "USA arrests", cex = 0.6, bty = "g", ticktype = "detailed", d = 2, clab = c("Urban","Pop"), adj = 0.5, font = 2)) with(USArrests, scatter3D(Murder, Assault, Rape - 1, colvar = UrbanPop, col = gg.col(100), type = "h", pch = ".", add = TRUE)) plotdev(xlim = c(0, 10), ylim = c(40, 150), zlim = c(7, 25))

140 scatter3D之四

141 Lattice套組 attach(quakes) library(lattice)
plot(xyplot(long~lat| cut(depth,2))) Magnitude=equal.count(mag,6) plot(cloud(depth~lat* long| Magnitude, panel.aspect=0.9)) plot(cloud(depth~lat* long| cut(mag,4),panel.aspect=0.9)) summary(Deep) plot(lat~long,pch='+') symbols(long,lat,circles=depth,inches=0.5,add=T)

142 Lattice兩格

143 Lattice六格

144 Lattice四格

145 Lattice四格

146 Bubble plot

147 多張圖可利用迴圈執行

148 一張紙15個圖形(但有兩張)

149 兩張紙30個圖形輸出到pdf檔 wdbc=read.csv(“d:\\stella\\R\\wdbc.txt”, header=T)
head(wdbc) pdf("d:\\stella\\R\\wdbc.pdf") par(mai=c(0.5,0.5,0.5,0.5),mfrow=c(3,5)) for (i in 3:32) { hist(wdbc[ ,i],main=paste("C",i-2)) } graphics.off()

150 迴圈繪圖(多個檔在同一目錄) # method 1:all files of one directory
(dir=list.files("d:/stella/R/baby",full.name=TRUE)) # infile=dir[grep(“.txt”,dir)] par(mai=c(0.5,0.5,0.5,0.5),mfrow=c(3,4)) lbl=c("~20","20~25","25~30","30~35","35~40","40~") for (i in 1:length(dir)) { file0=dir[i]; data=read.table(file=file0,header=T) hist(data$bwt,main=paste("babies weight hist age=",lbl[i])) plot(data$height,data$weight,main=paste("height and weight plot age=",lbl[i])) }

151 baby1.txt-baby6.txt對應先前用
迴圈繪圖(多個檔在同一目錄) baby1.txt-baby6.txt對應先前用 subset函數輸出的檔grp1-grp6

152 迴圈繪圖(利用循序的檔名) #method 2:seqential file names利用循序檔名
pdf("d:\\stella\\R\\baby\\babies.pdf") # ,family=“GB1” par(mai=c(0.5,0.5,0.5,0.5),mfrow=c(3,2)) lbl=c("~20","20~25","25~30","30~35","35~40","40~") for (i in 1:6) { fn=paste("d:\\stella\\R\\baby\\baby",i,".txt",sep=""); data=read.table(file=fn,header=T) hist(data$bwt,main=paste("babies weight hist age=",lbl[i])) plot(data$height,data$weight,main=paste("height and weight plot age=",lbl[i])) } graphics.off() # or dev.off()

153 迴圈繪圖的結果

154 練習:wdbc盒狀圖 pdf("d:\\stella\\output.pdf")
par(mai=c(0.5,0.5,0.5,0.5),mfcol=c(2,3)) for (i in 3:32) { boxplot(wdbc[,i]~wdbc[,2],main=paste("c",i-2,sep=""),col=c("yellowgreen","gray")) boxplot(wdbc[,i], main=paste("c",i-2,sep=""), col="yellow",boxwex=0.3) boxplot(wdbc[diagnosis==“M”,i],col=“blue”,boxwex= 0.1, at= c(1.3), add=TRUE, axes=F) boxplot(wdbc[diagnosis==“B”,i],col=“pink”,boxwex= 0.1, at= c(0.7), add=TRUE, axes=F) } graphics.off()

155


Download ppt "R軟體基本使用 R軟體安裝與基本使用 R基本運算和變數種類 R的版面配置與繪圖功能 4 2 3 1 資料輸出入與資料處理."

Similar presentations


Ads by Google