1.基础运算
- 算术运算
>1+1
[1] 2
>1-1
[1] 0
- 比较运算
# == != >= <= > <
#
> 1>2
[1] FALSE
> T = True
[1] True
- 逻辑运算
# |或 &与 !否
- 变量
> a <- 1
> a
[1] 1
>a <- 'dongge'
>a
[1] dongge
2. 序列和向量
- 序列sequence
>5:9
[1] 5 6 7 8 9
>seq(5,9)
[1] 5 6 7 8 9
>seq(5,9,0.5)
[1] 5.0 5.5 6.0 6.5 7.0 7.5 8.0 8.5 9.0
- 向量vector
>c(4,5,6)
[1] 4 5 6
>c(1,True,'abc')
[1] 1 True abc
> a <- 1:3
序列跟向量类似,可以通用相关操作。
- 向量基本操作(访问,修改,增加)
> sentence <- c('walk', 'the', 'plank')
> sentence[3]
[1] plank
> sentence[1]
[1] walk
> sentence[3] = 'zeus' #修改元素
> sentence[4] = 'dog'#增加元素
> sentence[c(1,3)]#可以用向量来获取多个元素
# ‘walk’ ‘zeus’
> sentence[1:3]
# walk the zeus
> sentence[5:7] <- c('the', 'poop', 'deck')
- 向量命名
> sentence <- c('dongge',31,'male')
> names(sentence) <- c('name','age','gender')
> sentence['name']
'dongge'
- 向量的简单绘图
> vesselsSunk <- c(4, 5, 1)
> barplot(vesselsSunk)
给每个柱形图添加名称
> names(vesselsSunk) <- c('England','France','Norway')
> barplot(vesselsSunk)
- 向量的算术运算
> a <- c(1,2,3)
> a + 1
[1] 2,3,4
> a / 2
[1] 0.5 1.0 1.5
> b <- c(4,5,6)
> b - a
[1] 3 ,3 ,3
> a == c(4,5,6)
[1] False False False
> sin(a)
[1] 0.8414710 0.9092974 0.1411200
绘点图
a = seq(1,9,0.1)
y <- sin(a)
plot(a,y)
- NA值
> sum(c(1,2,NA)
[1] NA
sum函数不会默认把NA值排除之后进行运算,这里可以设定其中的参数na.rm
> sum(c(1,2,NA),na.rm=TRUE)
[1] 3
3.矩阵
-
建立矩阵
a.直接用matrix建立矩阵
> matrix(1,3,4)
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 1 1 1 1
[3,] 1 1 1 1
b.通过变换向量建立矩阵
> a <- 1:12
> matrix(a,3,4)
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
c.直接设定维度
> plank <- 1:8
> dim(plank) <- c(2,4)
> print(plank)
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
-
矩阵的访问
> print(plank)
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
> plank[2,3]
[1] 6
> plank[1,4] <- 0 #修改
> plank[2,] #取一行,注意``,``号
[1] 2 4 6 8
> plank[,4]#取一列
[1] 7 8
> plank[,2:4] #取多列
[,1] [,2] [,3]
[1,] 3 5 7
[2,] 4 6 8
-
矩阵绘图
> elevation <- matrix(1,10,10)
> elevation[4,6] <- 0
> contour(elevation)#轮廓图
> persp(elevation)#三维图
> persp(elevation, expand=0.2)
4. 统计
- 平均数
> limbs <- c(4, 3, 4, 3, 2, 4, 4, 4)
> names(limbs) <- c('One-Eye', 'Peg-Leg', 'Smitty', 'Hook', 'Scooter', 'Dan', 'Mikey', 'Blackbeard')
> barplot(limbs)
>abline(h = mean(limbs))#画一条水平平均线
- 中位数
有时候平均数并不能很好表达数据的实际情况,比如数据差距很大。
> limbs <- c(4, 3, 4, 3, 2, 4, 4, 14)
> names(limbs) <- c('One-Eye', 'Peg-Leg', 'Smitty', 'Hook',
'Scooter', 'Dan', 'Mikey', 'Davy Jones')
> mean(limbs)
[1] 4.75
> barplot(limbs)
> abline(h = mean(limbs))
求解中位数
> median(limbs)
[1] 4
> abline(h = median(limbs))
- 标准差
> pounds <- c(45000, 50000, 35000, 40000, 35000, 45000, 10000, 15000)
> barplot(pounds)
> meanValue <- mean(pounds)
> deviation <- sd(pounds)
> abline(h = meanValue + deviation)
![Upload Paste_Image.png failed. Please try again.]