R有多种存储数据的对象类型。基本的类型可分为:
1.向量
向量中的数据必须拥有相同类型或模式(数值型、字符型、逻辑型);
向量类似c语言中的数组;实例:
>a<-c(1,2,3,4,5,6)
>b<-c(“one”,”two”,”three”)
>c<-c(TURE,FALSE,TRUE)
标量是指只含一个元素的向量;实例:
>e<-3
访问向量中的元素(向量中的元素从1开始,这点与数组不同):
>a<-c(1,2,5,7,-5,4) >a[3]
[1] 5
>a[c(1,3,4)]
[1] 1 5 7
>a[2:5]
[1] 2 5 7 -5
2.矩阵
矩阵相当于二维向量,创建矩阵方法如下:
mymatrix<-matrix(vector,nrow=number_of_rows,ncol=number_of_columns,
byrow=TURE_or_FALSE,dimnames=list
char_vector_rownames,char_vector_colnames))
实例:
>m<-matrix(data=1:12,nrow=4,ncol=3,
+dimnames=list(c(“r1″,”r2″,”r3″,”r4″),
+c(“c1″,”c2″,”c3″))
>m
c1 c2 c3
r1 1 5 9
r2 2 6 10
r3 3 7 11
r4 4 8 12
矩阵下标的使用:
> 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[1,4]
[1] 7
> x[1,c(4,5)]
[1] 7 9
3.数组
数组与矩阵类似,但是维度可以大于2,创建数组实例:
> 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
从数组中选取元素的方式与矩阵相同,上例中,元素z[1,2,3]为10;
4.数据框
数据框的不同列可以包含不同模式(数值型、字符型等)的数据,创建数据框:
> patientID<-c(1,2,3,4)
> age<-c(24,35,28,41)
> diabetes<-c(“Type1″,”Type2″,”Type1″,”Type1″)
> status<-c(“Poor”,”Improved”,”Excellent”,”Poor”)
> patientdata<-data.frame(patientID,age,diabetes,status)
> patientdata
patientID age diabetes status
1 1 24 Type1 Poor
2 2 35 Type2 Improved
3 3 28 Type1 Excellent
4 4 41 Type1 Poor
选取数据框中的元素:
> patientdata[1:2]
patientID age
1 1 24
2 2 35
3 3 28
4 4 41
> patientdata[c(“diabetes”,”status”)]
diabetes status
1 Type1 Poor
2 Type2 Improved
3 Type1 Excellent
4 Type1 Poor
> patientdata$age
[1] 24 35 28 41
5.因子
因子即将变量的值以整数表示,可以分为有序型(即变量值存在顺序关系)和名义型(变量的值仅仅是个代号,没有顺序大小之分)。实例如下:
>diabetes<-c(“Type1″,”Type2″,”Type1″,”Type1″)
> diabetes<-factor(diabetes) > diabetes
[1] Type1 Type2 Type1 Type1
Levels: Type1 Type2
6.列表
列表是不同对象的有序集合。列表创建如下:
> g<-“My first list”
> h<-c(24,34,52,45)
> j<-matrix(1:10,nrow=5)
> k<-c(“one”,”two”,”three”)
> mylist<-list(title=g,ages=h,j,k)
> mylist
$title
[1] “My first list”
$ages
[1] 24 34 52 45
[[3]]
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[[4]]
[1] “one” “two” “three”
列表元素的取出:
> mylist[[2]]
[1] 24 34 52 45
> mylist[[“ages”]]
[1] 24 34 52 45