2.2.1向量
向量是用于存储数值型、字符型火逻辑型数据的一维数组。
> a <- c(1,2,5,3,6,2,4)
> a
[1] 1 2 5 3 6 2 4
> a[3]
[1] 5
> a[c(1,2,3)]
[1] 1 2 5
> a[c(1:4)]
[1] 1 2 5 3
2.2.2矩阵
矩阵式一个二维数组,只是每个元素都拥有相同的模式(数值型,字符型或逻辑型),可通过函数matrix创建矩阵。
创建矩阵
> y<-matrix(1:20,nrow=5,ncol=4)
> y
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
> cells<-c(1:4)
> rnames<-c("R1","R2")
> cnames<-c("C1","C2")
> mamatrix<-matrix(cells,nrow=2,ncol=2,byrow=TRUE,dimnames=list(cnames,rnames))
> mamatrix
R1 R2
C1 1 2
C2 3 4
> mamatrix<-matrix(cells,nrow=2,ncol=2,byrow=FALSE,dimnames=list(cnames,rnames))
> mamatrix
R1 R2
C1 1 3
C2 2 4
矩阵下标使用
> x<-matrix(1:10,nrow=2)
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> x[2,]
[1] 2 4 6 8 10
> x[,2]
[1] 3 4
> x[1,4]
[1] 7
> x[1,c(2:4)]
[1] 3 5 7
2.2.3数组
数组(array)与矩阵类似,但是维度可以大于2,数组可通过array函数创建。
dim1<-c("A1","A2")
dim2<-c("B1","B2","B3")
dim3<-c("C1","C2","C3","C4")
z<-array(1:24,c(2,3,4),dimnames=list(dim1,dim2,dim3))
> z
, , C1
B1 B2 B3
A1 1 3 5
A2 2 4 6
, , C2
B1 B2 B3
A1 7 9 11
A2 8 10 12
, , C3
B1 B2 B3
A1 13 15 17
A2 14 16 18
, , C4
B1 B2 B3
A1 19 21 23
A2 20 22 24
2.2.4数据框
由于不同的列可以包含不同模式的数据,数据框的概念较矩阵来说更为一般。
作图
dose <- c(20,30,40,45,60)
drugA <- c(16,20,27,40,60)
plot(dose,drugA, type="b",
col="red",lty=2, pch=2,lwd=2,
main="大clinical trials for drug A",
sub="this is hypothetical data",
xlab="doseage", ylab="drug response",
xlim=c(0,60), ylim=c(0,70))
创建leadership数据框
manager <- c(1,2,3,4,5)
data <- c("10/24/08","10/28/08","10/1/08","10/12/08","5/1/09")
country <- c("US", "US", "UK", "UK", "UK")
gender <- c("M", "F", "F", "M", "F")
age <- c(32,45,25,39,99)
q1 <-c(5,3,3,3,2)
q2 <- c(4,5,5,3,2)
q3 <- c(5,2,5,4,1)
q4 <- c(5,5,5,NA,2)
q5 <- c(5,5,2,NA,1)
leadership <- data.frame(manager,data,country,gender,age,q1,q2,q3,q4,q5,stringsAsFactors=FALSE)