R Programming LanguageR程式语言.ppt

上传人:s****8 文档编号:82754231 上传时间:2023-03-26 格式:PPT 页数:92 大小:562KB
返回 下载 相关 举报
R Programming LanguageR程式语言.ppt_第1页
第1页 / 共92页
R Programming LanguageR程式语言.ppt_第2页
第2页 / 共92页
点击查看更多>>
资源描述

《R Programming LanguageR程式语言.ppt》由会员分享,可在线阅读,更多相关《R Programming LanguageR程式语言.ppt(92页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、R Programming LanguageR 程式語言程式語言林林 建建 甫甫C.F.Jeff Lin,MD.PhD.台台 北北 大大 學學 統統 計計 系系 助助 理理 教教 授授台台 北北 榮榮 民民 總總 醫醫 院院 生生 物物 統統 計計 顧顧 問問美美 國國 密密 西西 根根 大大 學學 生生 物物 統統 計計 博博 士士12/17/20221Jeff Lin,MD.PhD.R:物件導向程式語言物件導向程式語言 R as Objective-Oriented Language12/17/20222Jeff Lin,MD.PhD.R:基本基本(R Basics)物件命名與指派(Nam

2、ing and Assign)變數類型(Type of Variables)缺失值(Missing Values)資料輸入與指派(Assignment and Input Data)函數(Functions)工作路徑(Workspace)歷史紀錄(History)12/17/20223Jeff Lin,MD.PhD.物件命名物件命名 Naming Convention必須以英文字母起始(A-Z 或 a-z)中間可以任何文字與數字,點(periods)“.”大小寫有差別mydata 與 MyData 不同不可使用下線(do not use use underscore“_”)12/17/2022

3、4Jeff Lin,MD.PhD.物件指派物件指派 指派(避免使用)xyz.vector c(1,2,3)12/17/20225Jeff Lin,MD.PhD.未完成的指令或程式未完成的指令或程式 R 出現出現“+”若鍵入“return”,而 R 出現 “+”,表示輸入指令未完成,若查不出錯誤處,可議連續鍵入“return”,直到 R 出現 “”符號.如此再重新輸入 R 指令或程式.sqrt(+)Error in parse(text=txt):Syntax error:No opening parenthesis,before)at this point:sqrt()Dumped sqrt(

4、100)12/17/20226Jeff Lin,MD.PhD.物件物件 Objects物件名稱(names)物件種類(Type of Variables):向量,因子,陣列,矩陣,資料框架,時間序列,列表.(vector,factor,array,matrix,data.frame,ts,list)屬性(attributes)模式(mode):邏輯,整數,倍精準度,單精準度,複數,文字.(numeric,character,complex,logical)長度(Length):與物件的模式有關物件產生(creation):指派數值或空物件12/17/20227Jeff Lin,MD.PhD.a

5、 sqrt(a)1 7 b sub(dog,cat,b)1 The cat ate my homework x x1 FALSE as.character(b)1 FALSE數值數值 numeric文字與字串文字與字串character string邏輯 logical基本模式變數命名與指派12/17/20228Jeff Lin,MD.PhD.基本模式變數命名與指派Logical(邏輯)x-T;y x;y1 TRUE1 FALSENumerical(數值數值)a-5;b a;b1 51 1.414214Character 文字與字串文字與字串 a-1;b a;b1 11 1 a b-a;x a

6、;b;x1 character1 a1 character12/17/20229Jeff Lin,MD.PhD.物件指派物件指派 Assignment“x x x 10+20Multiply:10*20Divide:10/20Raise to a power:10*20Modulo:10%20Integer division:10%/%412/17/202212Jeff Lin,MD.PhD.R:邏輯操作邏輯操作 與與 關係比較操作關係比較操作=Equal to!=Not equal toGreater than=Greater than or equal tois.na(x)Missing?

7、&Logical AND|Logical OR!Logical NOT12/17/202213Jeff Lin,MD.PhD.缺失值缺失值 NA,NaN,與與 NullNA 或“Not Available”可用在許多模式(modes)character,numeric,etc.NaN 或“Not a Number”只用在數值模式(numeric modes)NULL列表(lists)的長度為 0(zero length)12/17/202214Jeff Lin,MD.PhD.缺失值缺失值 Missing Values,NA,NaN,與與 NullNA or“Not Available”Appl

8、ies to many modes character,numeric,etc.NaN or“Not a Number”Applies only to numeric modesNULLLists with zero length12/17/202215Jeff Lin,MD.PhD.缺失值缺失值 Missing ValuesNA“not available”x x+31 4 5 6 NA非數字“Not a number”log(c(0,1,2)1 -Inf 0.0000000 0.6931472 0/01 NaN12/17/202216Jeff Lin,MD.PhD.R:缺失值缺失值 Mis

9、sing ValuesNA 或“Not Available”NA 不是 0NA 不是“(空格,或 空字串)NA不是 FALSE任何與 NA 的計算,可能或不可能產生 NA 1+NA1 NA max(c(NA,4,7)1 NA max(c(NA,4,7),na.rm=T)1 712/17/202217Jeff Lin,MD.PhD.R:統計分析常見物件型態統計分析常見物件型態Common Object Types for Statistics12/17/202218Jeff Lin,MD.PhD.Types of Objects向量 Vector矩陣 Matrix陣列 Array列表 List因

10、子 Factor時間序列 Time series資料框架 Data frame函式 Function typeof(物件名稱)可已回傳物件型態12/17/202219Jeff Lin,MD.PhD.Mode 物件結構物件結構(模式模式)模式 Mode原型模式 Atomic Mode:logical,numeric,complex 或 character遞迴型 Recursive Mode list,graphics,function,expression,call.mode()指令可以用來查看物件的模式12/17/202220Jeff Lin,MD.PhD.物件長度物件長度(Length)長度

11、 Lengthvector:number of elementsmatrix,array:product of dimensionslist:number of componentsdata frame:number of columns12/17/202221Jeff Lin,MD.PhD.物件物件屬性屬性(Attribute)屬性 Attributes 列位名(row name),欄位名(column name),維度(dimension).row.names()names()str()12/17/202222Jeff Lin,MD.PhD.物件類別物件類別(Class)類別 Class物

12、件的類別方便 R 進行程式寫作.類別可以讓 R 得知物件的特殊性,使用特別的方法進行操作;例如,有一個物件,其類別是資料框架,則此物件會以特別形式列印.12/17/202223Jeff Lin,MD.PhD.向量向量 Vector 指包含相同 模式 的元素(element)組成序列.主要有 6 種基本模式(mode)logical,integer,double,single,complex,and character.(邏輯,整數,倍精準度,單精準度,複數,文字).向量是具有相同基本類型的元素序列,大體相當於其他語言中的 1-維度數列,在 R 中,單一數值(scalar)也可看成是長度為 1

13、的向量.12/17/202224Jeff Lin,MD.PhD.向量向量 Vector a a*21 2 4 6向量的產生最常用辦法是使用函式向量的產生最常用辦法是使用函式 c(),它把若干個它把若干個數值或字串組合為一個向量數值或字串組合為一個向量,12/17/202225Jeff Lin,MD.PhD.向量運算操作向量運算操作算數操作(arithmetic operator)符號包含+,-,*,/,%,%/%,%*%,%o%,%x%等.通常其含意是對向量的每一個元素進行運算的 單元運算子(unary)或 二元運算子(binary),如同一般算數運用在向量.向運有“長度”,但不具有“維度”.

14、12/17/202226Jeff Lin,MD.PhD.向量向量 Vectors Mydata Colors x1 x11 25 26 27 28 29 30#數字序列數字序列 Colors21“Green”#單一元素單一元素 x13:51 27 28 29#多各元素多各元素12/17/202227Jeff Lin,MD.PhD.12/17/202228Jeff Lin,MD.PhD.12/17/202229Jeff Lin,MD.PhD.12/17/202230Jeff Lin,MD.PhD.向量向量 Vectors x log(x)1 1.6486586 0.5306283 1.84054

15、96 y z y+z1 2.0 3.1 4.2 5.3 6.4 length(y)1 5 mean(y+z)1 4.212/17/202231Jeff Lin,MD.PhD.12/17/202232Jeff Lin,MD.PhD.向量運算操作向量運算操作邏輯檢測抽出某一元素刪除元素 Mydata1 2 3.5-0.2 Mydata 0 1 TRUE TRUE FALSE MydataMydata01 2 3.5 Mydata-c(1,3)1 3.512/17/202233Jeff Lin,MD.PhD.向量運算操作向量運算操作 x y y1 10 20 30 40 sort(x)#重新排序重新

16、排序1-7-2 3 5 order(x)1 4 2 3 1#排順序後的位置排順序後的位置 yorder(x)1 40 20 30 10#rev(x)#反向反向1-7 3-2 512/17/202234Jeff Lin,MD.PhD.c()&rev()c(1,3,5,7)1 1 3 5 7 rev(c(1,3,5,7)1 7 5 3 112/17/202235Jeff Lin,MD.PhD.length(),mode()&names()x length(x)1 4 mode(x)1 numeric names(x)NULL12/17/202236Jeff Lin,MD.PhD.seq()seq(

17、)產生數字序列 seq(1:5)1 1 2 3 4 5 seq(5,1,by=-1)1 5 4 3 2 1 seq(5)1 1 2 3 4 512/17/202237Jeff Lin,MD.PhD.seq()1.1:51 1.1 2.1 3.1 4.1 4:-5 1 4 3 2 1 0-1-2-3-4-5 seq(-1,2,0.5)1-1.0-0.5 0.0 0.5 1.0 1.5 2.0 seq(1,by=0.5,length=5)1 1.0 1.5 2.0 2.5 3.012/17/202238Jeff Lin,MD.PhD.rep()rep()replicates elements re

18、p(1,5)1 1 1 1 1 1 rep(1:2,3)1 1 2 1 2 1 2 rep(1:2,each=3)1 1 1 1 2 2 2 rep(1:2,each=3,len=4)1 1 1 1 2 rep(1:2,each=3,len=7)1 1 1 1 2 2 2 1 rep(1:2,each=3,time=2)1 1 1 1 2 2 2 1 1 1 2 2 212/17/202239Jeff Lin,MD.PhD.sort()&rank()x sort(x)1 6 7 8 9 rank(x)1 3 1 4 2 rank(x)11 3 xrank(x)=11 6 xrank(x)1 9

19、 8 7 612/17/202240Jeff Lin,MD.PhD.rank()&order()x order(x)1 2 4 1 3 rank(x)1 3 1 4 2 xorder(x)1 6 7 8 9 xrank(x)1 9 8 7 612/17/202241Jeff Lin,MD.PhD.矩陣矩陣 Matrix矩陣由包含相同的元素組成的 2-維(2-dimension)資料物件可由 matrix()產生 x x x x1 x3:5 x-(3:5)xc(T,F,T,F,T,F,T,F)xx m,2 m3,12/17/202243Jeff Lin,MD.PhD.Generate a Mat

20、rix xmat xmat ,1,2,3,41,1 2 3 42,5 6 7 83,9 10 11 12 length(xmat)1 12 dim(xmat)1 3 4 mode(xmat)1 numeric names(xmat)NULL dimnames(xmat)NULL12/17/202244Jeff Lin,MD.PhD.Generate a Matrix matrix(0,3,3),1,2,31,0 0 02,0 0 03,0 0 012/17/202245Jeff Lin,MD.PhD.Generate a Matrix dimnames(xmat)dimnames(xmat)1

21、1 A B C21 W X Y Z xmat W X Y ZA 1 2 3 4B 5 6 7 8C 9 10 11 1212/17/202246Jeff Lin,MD.PhD.Diagonal Element of a Matrix m m ,1,2,31,1 2 32,4 5 63,7 8 94,10 11 12 diag(m)1 1 5 912/17/202247Jeff Lin,MD.PhD.Diagonal Element of a Matrix diag(k),1,2,31,1 0 02,0 1 03,0 0 112/17/202248Jeff Lin,MD.PhD.Inverse

22、of Matrices m m ,1,2,31,1 3 52,9 11 133,15 19 21 solve(m),1 ,2,31,-0.5000 1.0000-0.52,0.1875-1.6875 1.03,0.1875 0.8125-0.512/17/202249Jeff Lin,MD.PhD.rbind()&cbind()x y rbind(y,x),1,2,3 0 0 0 0 0 0 0 0 0 x 1 2 3 cbind(y,x)x1,0 0 0 12,0 0 0 23,0 0 0 312/17/202250Jeff Lin,MD.PhD.Multiplication x y x*y

23、#element wise ,1,21,1 42,9 16 x%*%y#,1,21,7 102,15 2212/17/202251Jeff Lin,MD.PhD.x%o%x,1,1 ,1,21,1 22,3 4,2,1 ,1,21,3 62,9 12,1,2 ,1,21,2 42,6 8,2,2 ,1,21,4 82,12 1612/17/202252Jeff Lin,MD.PhD.ArrayArrays are generalized matrices by extending the function dim()to mor thantwo dimensions.xarr xarr,1 ,

24、1 ,2,3,41,1 3 5 72,2 4 6 8,2 ,1 ,2 ,3,41,11 13 15 172,12 14 16 18,3 ,1 ,2 ,3 ,41,111 113 115 1172,112 114 116 11812/17/202253Jeff Lin,MD.PhD.列表列表 Lists12/17/202254Jeff Lin,MD.PhD.列表列表 Lists列表是一個特殊的 向量,這特殊的向量中的元素是物件.因此列表物件是由資料物件有順序組成,列表物中的 元素,稱作 成份(component)是物件本身.是有順序的(order sequence).成份物件的元素模式,沒有任合

25、限制,每一個別成份的物件之原型模式可以不相同.12/17/202255Jeff Lin,MD.PhD.列表列表 Lists doe doe$name1 john“doe$age1 28 doe31 FALSE列表由列表由“$”抽取元素抽取元素12/17/202256Jeff Lin,MD.PhD.列表列表 Listsvector:指包含相同 模式 的元素(element)組成序列.a=c(7,5,1)a21 5list:列表是一個特殊的 向量,這特殊的向量中的元素是物件.doe=list(name=john,age=28,married=F)doe$name1 john“doe$age1 28

26、12/17/202257Jeff Lin,MD.PhD.列表列表 Lists my.list my.list1:1 5 4-12:1 X1 X2 X3 my.list11 5 4-1 my.list my.list$c22:31 X2 X312/17/202258Jeff Lin,MD.PhD.列表列表 Lists x.mat ,1,2 1,3 -12,2 03,-3 6 dimnames(x.mat)x.mat R1 R2 L1 3-1L2 2 0L3-3 612/17/202259Jeff Lin,MD.PhD.Lists,Factors and Data Frames12/17/2022

27、60Jeff Lin,MD.PhD.因數因數 或或 因子因子 Factor and factor()處理類別資料,提供的一種有效的方法.因為統計中的離散變數(discrete variable)名義變數(nominal variable)與 有序變數(ordinal variable).因素/因子 是一種特殊的文字向量,文字向量中每一個元素,取一個離散值.因素物件有一個特殊屬性 層次/水平/水準(levels)表示這組所有的離散值.因數可以簡單地用函式 factor()產生.因素/因子 是用 文字/字串 輸入,一但設定為因素/因子向量,R 列印時,並不會加上雙引號.12/17/202261Je

28、ff Lin,MD.PhD.因數因數 或或 因子因子 Factor and factor()gender gender1 male female male male female female factor(gender)1 male female male male female femaleLevels:female male12/17/202262Jeff Lin,MD.PhD.factor()and levels()intensity intensity1 Hi Med Lo Hi Lo Med Lo Hi MedLevels:Hi Lo Med12/17/202263Jeff Lin

29、,MD.PhD.factor()and levels()intensity intensity1 Hi Med Lo Hi Lo Med Lo Hi MedLevels:Hi Med Lo12/17/202264Jeff Lin,MD.PhD.factor()and levels()intensity intensity1 HiDOse MedDOse LoDose HiDOse LoDose MedDOse LoDose HiDOse MedDOseLevels:HiDOse MedDOse LoDose12/17/202265Jeff Lin,MD.PhD.factor(),ordered

30、()and levels()intensity intensity1 Hi Med Lo Hi Lo Med Lo Hi MedLevels:Hi Lo MedOooooop!This is not what you want!12/17/202266Jeff Lin,MD.PhD.factor(),ordered()and levels()intensity intensity1 Hi Med Lo Hi Lo Med Lo Hi MedLevels:Lo Med ToothGrowth len supp dose1 4.2 VC 0.52 11.5 VC 0.53 7.3 VC 0.54

31、5.8 VC 0.558 27.3 OJ 2.059 29.4 OJ 2.060 23.0 OJ 2.012/17/202270Jeff Lin,MD.PhD.Data Frames A data frame is a list with class“data.frame”.There are restrictions on lists that may be made into data frames.a.The components must be vectors(numeric,character,or logical),factors,numeric matrices,lists,or

32、 other data frames.b.Matrices,lists,and data frames provide as many variables to the new data frame as they have columns,elements,or variables,respectively.12/17/202271Jeff Lin,MD.PhD.Data Frames c.Numeric vectors and factors are included as is,and non-numeric vectors are coerced to be factors,whose

33、 levels are the unique values appearing in the vector.d.Vector structures appearing as variables of the data frame must all have the same length,and matrix structures must all have the same row size.12/17/202272Jeff Lin,MD.PhD.Data Frameseveral modes allowed within a single data framecan be created

34、using data.frame()L-LETTERS1:4#A B C Dx3)12/17/202274Jeff Lin,MD.PhD.Individual elements of a vector,matrix,array or data frame are accessed with“”by specifying their index,or their name ToothGrowth1:3,len supp dose1 4.2 VC 0.52 11.5 VC 0.537.3 VC 0.5 ToothGrowth1:2,1:2 len supp1 4.2 VC2 11.5 VCSubs

35、etting12/17/202275Jeff Lin,MD.PhD.Labels in Data Frames labels(ToothGrowth)1 1 1 2 3 4 5 6 7 8 9 10 11 1213 13 14 15 16 17 18 19 20 21 22 23 2425 25 26 27 28 29 30 31 32 33 34 35 3637 37 38 39 40 41 42 43 44 45 46 47 4849 49 50 51 52 53 54 55 56 57 58 59 6021 len supp dose12/17/202276Jeff Lin,MD.PhD

36、.Finding out about a data objectmode():tells you the storage mode of an object(i.e.whether it is a numeric vector,or a list etc.)attributes():provides information about the data objectclass():provides informaiton about the objects class.The class of an object often determines how the data object is

37、handled by a function.You can also set the objects mode,attributes or class using the above functions.e.g.mode(x)summary(data)names(data)attributes(data)Editing datafix(data)or edit(data)data$varattach(data)#in order to remove need of$detach(data)12/17/202282Jeff Lin,MD.PhD.Data Entry&Editingstart e

38、ditor and save changesdata.entry(x)start editor,changes not savedde(x)start text editoredit(x)12/17/202283Jeff Lin,MD.PhD.The attach and detach functionsThe attach function makes all the objects in a list or data frame accessible from outside the list or data frame.E.g.instead of typing my_list$age

39、to access the vector age in the list my_list you can just type age(provided there is no other vector called age in the main workspace).The detach function undoes this12/17/202284Jeff Lin,MD.PhD.Importing Dataread.table()reads in data from an external filedata.entry()create object first,then enter da

40、tac()concatenatescan()prompted data entryR has ODBC for connecting to other programs12/17/202285Jeff Lin,MD.PhD.Importing Data#Data Managements setwd(C:/temp/Rdata)DMTKRtable DMTKRtable12/17/202286Jeff Lin,MD.PhD.12/17/202287Jeff Lin,MD.PhD.Importing Data setwd(C:/temp/Rdata)DMTKRcsv DMTKRcsv attach

41、(DMTKRcsv)scan(file=DMTKRcsv.csv,skip=1,sep=,dec=.)12/17/202288Jeff Lin,MD.PhD.LoadingStata,SPSS,SAS filesLibrary(foreign)Stata:read.dtaSPSS:read.spssSAS:read.xport(must first create export file in SAS)Excel filesFiles must be saved as comma separated value or.csv read.table,read.csv,read.csv2:ident

42、ical except for defaultsWatch the direction of/!load(“.Rdata”)Loading and running R programssource(“.R”)12/17/202289Jeff Lin,MD.PhD.Writing data to a file(the write and write.table functions)Change directory on the file menu thenwrite(q,file=“filename”,ncol=2)(for vector,ncol specifies the number of

43、 columns in output)write.table(q,file=“filename”)(works quite well for a data frame)as always there are many optional arguments 12/17/202290Jeff Lin,MD.PhD.Exporting Data#write data out cat(2 3 5 7,11 13 17 19,file=ex.dat,sep=n)#Read in ex.dat again scan(file=ex.dat,what=list(x=0,y=,z=0),flush=TRUE)df-data.frame(a=I(a quote)write.table(df)write.table(df,qmethod=double)write.table(df,quote=FALSE,sep=,)12/17/202291Jeff Lin,MD.PhD.Thanks!12/17/202292Jeff Lin,MD.PhD.

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 生活休闲 > 生活常识

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

© 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

黑龙江省互联网违法和不良信息举报
举报电话:0468-3380021 邮箱:hgswwxb@163.com