2 + 3 # 加法 52 3 # 乘法 6sqrt(36) # 开根号 6log10(100) # 10为底的对数运算 210 / 3 # 除法 3.3333333333333310 %/% 3 # 整除 310 %% 3 # 求余 1
56623.3333333333333331赋值运算符与大多数其他语言不同,R除了使用通常的=运算符赋值外,还使用<-或者->运算符在R语言中<-或者->运算符就相当于=号,唯一的区别是<-和->指明了运算方向==表示是否相等,=表示赋值a <- 10 # 把10赋值给aa = 10 # 把10赋值给a10 -> a # 把10赋值给a# 10 = a # 出错
数据类型R语言没有专门的步骤来定义变量的类型R会在后台直观地进行判断变量的类型我们可以通过class函数来查看变量的数据类型class(a) # numeric类型class(1.1) # numeric类型
‘numeric’‘numeric’根据分配给变量a的值,R决定将a分配为numeric类型如果您选择将其更改为字符’10’而不是数字10,则可以执行以下操作:a <- as.character(a) # 转换a为字符串print(a) # 打印a "10"class(a) # 数据类型 "character"
[1] "10"
‘character’当然我们也可以将a从字符串变为数字a <- as.numeric(a)print(a) # 打印a 10class(a) # 数据类型 "numeric"
[1] 10
‘numeric’常用的R语言类如下变量character 字符串integer 整数numeric 整数+分数factor 分类变量,其中每个级别都是一个类别logical 布尔complex 复数数据类别vector 同类元素的集合matrix 矩阵data.frame 类似excel中的二维表list 列表我们可以通过as.类型名来改变变量类型a<-as.matrix(a)print(a)class(a)
[,1][1,] 10
‘matrix’a<-as.logical(a)print(a)class(a)
[1] TRUE
‘logical’1.2 软件包的安装首次安装时,R附带有一组内置软件包,可以直接从R控制台调用它们但是,由于R是一种开放源代码语言,因此任何人都可以通过编写软件包来为其功能做出贡献多年来,这些贡献已导致超过5K软件包的清单不断增加这是从R控制台中安装软件包的方法注意不要在jupyter notebook中使用该代码,因为要选择cran镜像,很容易崩溃的#install.packages("car") # install car package
现在已经安装了该软件包,您需要对其进行初始化,然后才能调用已安装的软件包随附的函数和数据集library(car) # 初始化包require(car) # 另一种初始化方法#library() # 查看已经安装好的包#library(help=car) # 查看car包的帮助信息
Warning message:"package 'car' was built under R version 3.6.1"Loading required package: carDataWarning message:"package 'carData' was built under R version 3.6.1"
对于R语言可以直接输入代码查询包和函数的介绍信息#help(merge) # 查看merge的帮助信息#?merge # 从安装包中查找merge信息,和help类似#??merge # 模糊搜索example(merge) # 展示示例代码
merge> authors <- data.frame(merge+ ## I() : use character columns of names to get sensible sort ordermerge+ surname = I(c("Tukey", "Venables", "Tierney", "Ripley", "McNeil")),merge+ nationality = c("US", "Australia", "US", "UK", "Australia"),merge+ deceased = c("yes", rep("no", 4)))merge> authorN <- within(authors, { name <- surname; rm(surname) })merge> books <- data.frame(merge+ name = I(c("Tukey", "Venables", "Tierney",merge+ "Ripley", "Ripley", "McNeil", "R Core")),merge+ title = c("Exploratory Data Analysis",merge+ "Modern Applied Statistics ...",merge+ "LISP-STAT",merge+ "Spatial Statistics", "Stochastic Simulation",merge+ "Interactive Data Analysis",merge+ "An Introduction to R"),merge+ other.author = c(NA, "Ripley", NA, NA, NA, NA,merge+ "Venables & Smith"))merge> (m0 <- merge(authorN, books)) name nationality deceased title other.author1 McNeil Australia no Interactive Data Analysis <NA>2 Ripley UK no Spatial Statistics <NA>3 Ripley UK no Stochastic Simulation <NA>4 Tierney US no LISP-STAT <NA>5 Tukey US yes Exploratory Data Analysis <NA>6 Venables Australia no Modern Applied Statistics ... Ripleymerge> (m1 <- merge(authors, books, by.x = "surname", by.y = "name")) surname nationality deceased title other.author1 McNeil Australia no Interactive Data Analysis <NA>2 Ripley UK no Spatial Statistics <NA>3 Ripley UK no Stochastic Simulation <NA>4 Tierney US no LISP-STAT <NA>5 Tukey US yes Exploratory Data Analysis <NA>6 Venables Australia no Modern Applied Statistics ... Ripleymerge> m2 <- merge(books, authors, by.x = "name", by.y = "surname")merge> stopifnot(exprs = {merge+ identical(m0, m2[, names(m0)])merge+ as.character(m1[, 1]) == as.character(m2[, 1])merge+ all.equal(m1[, -1], m2[, -1][ names(m1)[-1] ])merge+ identical(dim(merge(m1, m2, by = NULL)),merge+ c(nrow(m1)nrow(m2), ncol(m1)+ncol(m2)))merge+ })merge> ## "R core" is missing from authors and appears only here :merge> merge(authors, books, by.x = "surname", by.y = "name", all = TRUE) surname nationality deceased title other.author1 McNeil Australia no Interactive Data Analysis <NA>2 R Core <NA> <NA> An Introduction to R Venables & Smith3 Ripley UK no Spatial Statistics <NA>4 Ripley UK no Stochastic Simulation <NA>5 Tierney US no LISP-STAT <NA>6 Tukey US yes Exploratory Data Analysis <NA>7 Venables Australia no Modern Applied Statistics ... Ripleymerge> ## example of using 'incomparables'merge> x <- data.frame(k1 = c(NA,NA,3,4,5), k2 = c(1,NA,NA,4,5), data = 1:5)merge> y <- data.frame(k1 = c(NA,2,NA,4,5), k2 = c(NA,NA,3,4,5), data = 1:5)merge> merge(x, y, by = c("k1","k2")) # NA's match k1 k2 data.x data.y1 4 4 4 42 5 5 5 53 NA NA 2 1merge> merge(x, y, by = "k1") # NA's match, so 6 rows k1 k2.x data.x k2.y data.y1 4 4 4 4 42 5 5 5 5 53 NA 1 1 NA 14 NA 1 1 3 35 NA NA 2 NA 16 NA NA 2 3 3merge> merge(x, y, by = "k2", incomparables = NA) # 2 rows k2 k1.x data.x k1.y data.y1 4 4 4 4 42 5 5 5 5 5
设置工作目录工作目录是R可以直接访问以读取文件的参考目录您可以在不使用完整文件路径的情况下直接将文件读取和写入文件到工作目录目录名称应使用正斜杠/或反斜杠分隔\,对于Windows也应如此# getwd() # 获得当前工作目录# setwd(dirname) # 设置工作目录
如何导入和导出数据将数据引入R的最常见,最方便的方法是通过.csv文件有一些软件包可以从excel文件(.xlsx)和数据库中导入数据,但此处不介绍a <- 1:3b <- (1:3)/5c <- c("row1", "row2", "row3")# 建立dataframedata <- data.frame(a, b, c)data
A data.frame: 3 × 3# 将data保存为csv文件write.csv(data, file="d:/data.csv", row.names = FALSE)# 将data保存为txt文件,sep表示用sep分割列write.table(data, file ="d:/data.txt", sep =",", row.names =FALSE)
# 读取csv文件data <- read.csv("d:/data.csv", header=FALSE)data
A data.frame: 4 × 3# 读取txt文件data <- read.table(file ="d:/data.txt", header = TRUE, sep=",", colClasses=c("integer","numeric","character"))data
A data.frame: 3 × 3vec1 <- c(10, 20, 15, 40) # 数字向量vec1vec2 <- c("a", "b", "c", NA) # 字符向量vec2vec3 <- c(TRUE, FALSE, TRUE, TRUE) # 逻辑向量vec3vec4 <- gl(4, 1, 4, label = c("l1", "l2", "l3", "l4")) # 因子向量vec4vec5 <- c(4111, "2", 4) # 混合变量vec5
10201540'a''b''c'NATRUEFALSETRUETRUEl1l2l3l4Levels:'l1''l2''l3''l4''4111''2''4'如何引用向量的元素?向量的元素可以使用其索引进行访问向量的第一个元素的索引为1,最后一个元素的索引值为length(vectorName)这一点和其他语言不一样,R语言索引从1开始索引变量名[i,j]表示索引从i到j的值vec1length(vec1) # 4print(vec1[1]) # 10print(vec1[1:3]) # 10, 20, 15
102015404[1] 10[1] 10 20 15
此外有时候我们需要初始化一个定长的向量,做法如下# 生成长度为10的向量,用0填充numericVector <- numeric(10)numericVector
00000000002.2 操纵向量子集vec1logic1 <- vec1 < 16 # 创建一个逻辑向量,小于16为true,反之falselogic1
10201540TRUEFALSETRUEFALSEvec1[logic1] # 读取位置为true的元素vec1[1:2] # 读取第一个和第二个元素vec1[c(1,3)] # 读取第一个和第三个元素vec1[-1] # 返回所有元素,除了第一个-1表示排除第一个元素,和其他语言不一样
101510201015201540排序sort(vec1) # 从小到大排序sort(vec1, decreasing = TRUE) # 从大到小排序
1015204040201510排序也可以使用order()函数实现,该函数以升序返回元素的索引vec1[order(vec1)] # 从小到大vec1[rev(order(vec1))] # 从大到小
1015204040201510创建向量序列和重复值seq()和rep()函数用于创建自定义向量序列rep()函数也可用于生成重复字符seq(1, 10, by = 2) # 创建1到10的向量序列,步长为2seq(1, 10, length=5) # 创建1到10的向量序列,等间隔获得5个值rep(1, 5) # 重复1,次数5次rep(1:3, 2) # 重复1到3,次数两次rep(1:3, each=2) # 重复1到3,每个数字重复两次
1357913.255.57.751011111123123112233如何删除缺失值可以使用is.na()函数来处理缺失值,该函数会在缺失值(NA)的位置返回逻辑值为TRUE的逻辑向量vec2 <- c("a", "b", "c", NA) # character vectoris.na(vec2) # missing TRUE!is.na(vec2) # missing FALSEvec2[!is.na(vec2)] # 返回非NA的元素
FALSEFALSEFALSETRUETRUETRUETRUEFALSE'a''b''c'采样set.seed(42) # 设置随机数种子,以vec1sample(vec1) # 随机从vec1中抽取所有数sample(vec1, 3) # 随机不放回从vec1中抽取3个数sample(vec1, 5, replace=T) # 随机放回从vec1中抽取5个数
102015401040152020401510401540152.3 数据框dataframe创建数据框并访问行和列数据框是执行各种分析的方便且流行的数据对象诸如read.csv()之类的导入语句会将数据作为数据帧导入R中,因此保持这种方式很方便现在,使用我们之前创建的向量创建一个数据框vec1vec2vec3vec4
10201540'a''b''c'NATRUEFALSETRUETRUEl1l2l3l4Levels:'l1''l2''l3''l4'# 每一个向量组成一列myDf1 <- data.frame(vec1, vec2) myDf1myDf2 <- data.frame(vec1, vec3, vec4)myDf2myDf3 <- data.frame(vec1, vec2, vec3)myDf3
A data.frame: 4 × 2library(datasets) # 初始化#library(help=datasets) # 展示数据集信息# 展示数据集头部六行head(airquality)
A data.frame: 6 × 6class(airquality) # dataframe类型sapply(airquality, class) # 获得dataframe每一列的类型str(airquality) # dataframe的结构
‘data.frame’'integer' Solar.R 'integer' Wind 'numeric' Temp 'integer' Month 'integer' Day 'integer''data.frame': 153 obs. of 6 variables: $ Ozone : int 41 36 12 18 NA 28 23 19 8 NA ... $ Solar.R: int 190 118 149 313 NA NA 299 99 19 194 ... $ Wind : num 7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ... $ Temp : int 67 72 74 62 56 66 65 59 61 69 ... $ Month : int 5 5 5 5 5 5 5 5 5 5 ... $ Day : int 1 2 3 4 5 6 7 8 9 10 ...
summary(airquality) # 数据集各列总结#fix(airquality) # 类似excel的方式展示数据集
Ozone Solar.R Wind Temp Min. : 1.00 Min. : 7.0 Min. : 1.700 Min. :56.00 1st Qu.: 18.00 1st Qu.:115.8 1st Qu.: 7.400 1st Qu.:72.00 Median : 31.50 Median :205.0 Median : 9.700 Median :79.00 Mean : 42.13 Mean :185.9 Mean : 9.958 Mean :77.88 3rd Qu.: 63.25 3rd Qu.:258.8 3rd Qu.:11.500 3rd Qu.:85.00 Max. :168.00 Max. :334.0 Max. :20.700 Max. :97.00 NA's :37 NA's :7 Month Day Min. :5.000 Min. : 1.0 1st Qu.:6.000 1st Qu.: 8.0 Median :7.000 Median :16.0 Mean :6.993 Mean :15.8 3rd Qu.:8.000 3rd Qu.:23.0 Max. :9.000 Max. :31.0
rownames(airquality) # dataframe行名colnames(airquality) # dataframe列名nrow(airquality) # 行数ncol(airquality) # 列数
'1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24''25''26''27''28''29''30''31''32''33''34''35''36''37''38''39''40''41''42''43''44''45''46''47''48''49''50''51''52''53''54''55''56''57''58''59''60''61''62''63''64''65''66''67''68''69''70''71''72''73''74''75''76''77''78''79''80''81''82''83''84''85''86''87''88''89''90''91''92''93''94''95''96''97''98''99''100''101''102''103''104''105''106''107''108''109''110''111''112''113''114''115''116''117''118''119''120''121''122''123''124''125''126''127''128''129''130''131''132''133''134''135''136''137''138''139''140''141''142''143''144''145''146''147''148''149''150''151''152''153''Ozone''Solar.R''Wind''Temp''Month''Day'1536用cbind和rbind增加数据myDf1myDf2
A data.frame: 4 × 2cbind(myDf1, myDf2) # 按列合并rbind(myDf1, myDf1) # 按行合并
A data.frame: 4 × 5myDf1
A data.frame: 4 × 2myDf1$vec1 # 提取列vec1myDf1[, 2] # 提取数据df[row.num, col.num]
10201540abc<NA>Levels:'a''b''c'myDf1[, c(1,2)] # 提取第一列和第二列myDf1[c(1:5), c(1)] # 提取第一列的1到5行,
A data.frame: 4 × 2head(airquality)
A data.frame: 6 × 6subset(airquality, Day == 1, select = -Temp)
A data.frame: 5 × 5which(airquality$Day==1)airquality[which(airquality$Day==1), -c(4)]
1326293124A data.frame: 5 × 5set.seed(100)trainIndex <- sample(c(1:nrow(airquality)), size=nrow(airquality)0.7, replace=F) # 获得验证集数据,比例0.7trainIndex
102112151455709813574314051252681394832859112116116934530128130879597124299231544110511724144145636591532014788833627465910069471499613812142132562282531035442852141421557793726114120109122111355874137123901187512710118899771431911923726684106# 训练数据nrow(airquality[trainIndex, ])# 测试数据nrow(airquality[-trainIndex, ])
10746合并数据dataframe可以由公共列变量合并在执行合并之前,不必对数据帧进行排序如果“by”列具有不同的名称,则可以使用by.x和by.y指定它们内部/外部联接、左联接和右联接可以使用merge()的all、all.x、all.y参数完成在R控制台中查看更多关于example(merge)的信息myDf1myDf2
A data.frame: 4 × 2merge(myDf1, myDf2, by="vec1") # 以vec1合并
A data.frame: 4 × 4paste("a", "b") # 拼接字符串'a'和'b'包含空格 "a b"paste0("a", "b") # 无空格拼接字符串'a'和'b', "ab"paste("a", "b", sep="") # sep设置拼接符是什么,类似paste0paste(c(1:4), c(5:8), sep="") # "15" "26" "37" "48"paste(c(1:4), c(5:8), sep="", collapse="") # "15263748"paste0(c("var"), c(1:5)) # "var1" "var2" "var3" "var4" "var5"paste0(c("var", "pred"), c(1:3)) # "var1" "pred2" "var3"paste0(c("var", "pred"), rep(1:3, each=2)) # "var1" "pred1" "var2" "pred2" "var3" "pred3
‘a b’‘ab’‘ab’'15''26''37''48'‘15263748’'var1''var2''var3''var4''var5''var1''pred2''var3''var1''pred1''var2''pred2''var3''pred3'3.2 处理日期dateString <- "07/02/2021"myDate <- as.Date(dateString, format="%d/%m/%Y") # 设置字符串class(myDate) # 类别 "date"myDate
‘Date’2021-02-073.3 制作列连表通过R语言的table函数可以制作列连表myDf1
A data.frame: 4 × 2table(myDf1)
vec2vec1 a b c 10 1 0 0 15 0 0 1 20 0 1 0 40 0 0 0
同样,对于dataframe,要在行中显示的变量将作为table()的第一个参数,而列变量将作为第二个参数table(airquality$Month[c(1:60)], airquality$Temp[c(1:60)])
56 57 58 59 61 62 64 65 66 67 68 69 72 73 74 75 76 77 78 79 80 81 82 84 85 5 1 3 2 2 3 2 1 1 3 2 2 2 1 1 2 0 1 0 0 1 0 1 0 0 0 6 0 0 0 0 0 0 0 1 0 1 0 0 1 2 1 1 4 3 2 2 2 0 2 1 1 87 90 92 93 5 0 0 0 0 6 2 1 1 1
3.4 列表列表非常重要如果需要捆绑不同长度和类别的对象,则可以使用列表来实现myList <- list(vec1, vec2, vec3, vec4)myList
10201540'a''b''c'NATRUEFALSETRUETRUEl1l2l3l4Levels:'l1''l2''l3''l4'3.5 If-Else语句if else语句结构如下if(checkConditionIfTrue) { ....statements.. ....statements..} else { # place the 'else' in same line as '}' ....statements.. ....statements..}
x<-2if(x>1) { print(x)}else { print("None")}
[1] 2
3.6 for循环格式如下for(counterVar in c(1:n)){ .... statements..}
for (x in c(1:5)) { print(x)}
[1] 1[1] 2[1] 3[1] 4[1] 5
3.7 apply类别函数applyapply():按数据行或矩阵按行或列应用函数myData <- matrix(seq(1,16), 4, 4) # 生成一个矩阵myData
A matrix: 4 × 4 of type intapply(myData, 1, FUN=min) # 1代表行,按行应用min函数apply(myData, 2, FUN=min) # 2代表列,按列应用min函数
123415913apply(data.frame(1:5), 1, FUN=function(x) {x^2} ) # square of 1,2,3,4,5
1491625lapply()lapply():将函数应用于列表中的每个元素,或将其应用于数据框的列,并将结果作为列表返回lapply(airquality, class)
'integer' $Solar.R 'integer' $Wind 'numeric' $Temp 'integer' $Month 'integer' $Day 'integer'sapplysapply():将函数应用于列表的每个元素,或将其应用于dataframe的列,并将结果作为向量返回sapply(airquality, class)
'integer' Solar.R 'integer' Wind 'numeric' Temp 'integer' Month 'integer' Day 'integer'3.8 使用tryCatch()处理错误该trycatch()函数在花括号内编写了三个块,try()我们前面看到的函数一样,可以在第一组花括号内使用多行代码如果在第一个块的任何一条语句中遇到错误,则生成的错误消息将存储在err错误处理函数使用的变量(请参见下面的代码)中您可以选择打印出此错误消息,进行其他计算或执行任何所需的操作您甚至还可以在此函数内执行一组完全不同的逻辑,而不涉及错误消息最后一组finally而不管是否发生错误,都必须执行您可以选择忽略将任何语句完全添加到此部分tryCatch( {1 <- 1; print("Lets create an error") }, # First blockerror=function(err){ print(err); print("Error Line")}, # Second Block(optional)finally = { print("finally print this")})# Third Block(optional)
<simpleError in 1 <- 1: (do_set)赋值公式左手不对>[1] "Error Line"[1] "finally print this"
4 参考R-Tutorial在 Jupyter Notebook 中使用R语言R语言个人笔记(图片来源网络,侵删)
0 评论