字串(character)
整數值(integer)
實數值(numeric)
邏輯值(logical)
複數值(complex)
位元組值(raw)
向量(vector)
#以":"創建向量,L代表整數(integer)
> (a<-0L:4L)
[1] 0 1 2 3 4
#以"C()"創建向量
> (a<-c(0,1,2,3,4))
[1] 0 1 2 3 4
矩陣(matrix)
#創建函數"matrix()"
#mymatrix<-matrix(向量物件,nrow=列數,ncol=行數,byrow=邏輯值,dimnames=list(列名字串向量,行名字串向量))
#以"paste0()"將字串與向量進行黏貼
> rnames<-paste0("row",1:5)
> cnames<-paste0("col",1:4)
> (mymatrix<-matrix(1:20,nrow=5,ncol=4,dimnames=list(rnames,cnames)))
col1 col2 col3 col4
row1 1 6 11 16
row2 2 7 12 17
row3 3 8 13 18
row4 4 9 14 19
row5 5 10 15 20
#預設為[列編號,]與[,行編號]
> (y<-matrix(1:20,nrow=5,ncol=4))
[,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
陣列(array)
#創建函數"array()"
#myarray<-array(向量物件,dim=各維因子水準數所形成的數值向量,dimnames=各維因子水準名稱之字串向量所形成的串列)
> dim1<-paste0("A",1:2)
> dim2<-paste0("B",1:3)
> dim3<-paste0("C",1:4)
> (myarray<-array(1:24,dim=c(2,3,4),dimnames=list(dim1,dim2,dim3)))
, , 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
串列(list)
#創建函數"list()"
#mylist<-list(元素名稱1=物件1,元素名稱2=物件2,...)
> g<-"My First List"
> h<-c(25,26,18,39)
> j<-matrix(1:10,nrow=5,byrow=T)
> k<-c("one","two","three")
> (mylist<-list(title=g,ages=h,j,k))
$title
[1] "My First List"
$ages
[1] 25 26 18 39
[[3]]
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[4,] 7 8
[5,] 9 10
[[4]]
[1] "one" "two" "three"
資料框(dataframe)
#創建函數"data.frame()"
#mydata<-data.frame(欄位名稱1=向量1,欄位名稱2=向量2,...)
> patientID<-c(1,2,3,4)
> age<-c(25,34,28,52)
> diabetes<-c("Type1","Type2","Type1","Type1")
> status<-c("Poor","Improved","Excellent","Poor")
> (mydata<-data.frame(patientID,age,diabetes,status))
patientID age diabetes status
1 1 25 Type1 Poor
2 2 34 Type2 Improved
3 3 28 Type1 Excellent
4 4 52 Type1 Poor
向量(vector)
#創建向量
> (x<-20:16)
[1] 20 19 18 17 16
#命名元素
> names(x)<-c("1st","2nd","3rd","4th","5th")
> x
1st 2nd 3rd 4th 5th
20 19 18 17 16
#單一位置取值
> x[4]
4th
17
#負索引,去掉第4項
> x[-4]
1st 2nd 3rd 5th
20 19 18 16
#單一名稱取值,有命名的話
> x["4th"]
4th
17
#連續範圍取值
> x[1:4]
1st 2nd 3rd 4th
20 19 18 17
#連續範圍移除
> x[-(1:4)]
5th
16
#位置索引取值
> x[c(1,4,2)]
1st 4th 2nd
20 17 19
#重複取值
> x[c(1,2,2,3,3,3,4,4,4,4)]
1st 2nd 2nd 3rd 3rd 3rd 4th 4th 4th 4th
20 19 19 18 18 18 17 17 17 17
#多名稱取值
> x[c("1st","3rd")]
1st 3rd
20 18
矩陣(matrix)
#創建函數"matrix()"
陣列(array)
#創建函數"array()"
串列(list)
#創建函數"list()"
資料框(dataframe)
#創建函數"data.