2014/11/16

[R] 第2篇 資料結構 (上)

R 的資料結構

1. 向量 Vector
利用 c() 來生成向量,利用 <- 傳入向量內容,同一向量必為同一型態。
## define different type vectors
> a <- c(0.1, 0.2)
> typeof(a)
[1] "double"
> b <- c(TRUE, FALSE)
> typeof(b)
[1] "logical"
> c <- c("a", "b", "c")
> typeof(c)
[1] "character"
## d is same as c(1, 2, 3)
> d <- c(1:3)
> typeof(d)
[1] "integer"
> e <- c(1+2i, 3+4i)
> typeof(e) 
[1] "complex"
> f <- c(1, "a", 2+3i)
> typeof(f) 
[1] "character"
> g <- c(1.7, "a")
> typeof(g) 
[1] "character"
> h <- c(TRUE, 2)
> typeof(h) 
[1] "double"
> i <- c("a", TRUE)
> typeof(i) 
[1] "character"
c() 生成的 vector 也能用在 [] 中,用來取元素。
> a <- c(1:10)
## same as a[2], a[3], a[4]
> a[c(2:4)]
[1] 2 3 4

2. 矩陣 Matrix
矩陣是二維的數據組,全部的元素型態皆為相同。Matrix 的宣告為 matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
data 為要放入的數據,nrow 是 row 的數目,ncol 是 column 的數目,byrow 是指數據是否依照 row 來放入,dimnames 是指 row 及 column 的 name。
## define a matrix, no input data, so default data is NA
> x <- matrix(nrow = 2, ncol = 3)
> x
     [,1] [,2] [,3]
[1,]   NA   NA   NA
[2,]   NA   NA   NA

## define a matrix,pass the data
> x <- matrix(1:6, nrow = 2, ncol = 3)
> x
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

## when byrow is TRUE, data is assign by row-first
> x <- matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE)
> x
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

## set the row and column name, use list to combine it
> rname <- c("r1", "r2")
> cname <- c("c1", "c2", "c3")
> x <- matrix(1:6, nrow = 2, ncol = 3, dimnames = list(rname, cname))
> x
   c1 c2 c3
r1  1  3  5
r2  2  4  6

## use c() to get the matrix's element
> x[1, 3]
[1] 5
> x[1, c(1:3)]
c1 c2 c3 
 1  3  5 
> x[,3]
r1 r2 
 5  6 

## another way to create matrix, use c() first then dim()
> x <- 1:6
> dim(x) <- c(2, 3)
> x
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

3. 陣列 Array
陣列與矩陣差不多,但陣列可以是二維以上的數據組,全部元素型態皆相同。Array 的宣告方式為 array(data = NA, dim = length(data), dimnames = NULL),跟 matrix 差不多,dim 是指維度。
## only pass the data, other is default setting, then it's a 1-dim array
> arr <- array(1:12)
> arr
 [1]  1  2  3  4  5  6  7  8  9 10 11 12
## define the dims' names, pass the data, dim and dims' names
> dim1 <- c("x1", "x2")
> dim2 <- c("y1", "y2", "y3")
> dim3 <- c("z1", "z2")
> arr <- array(1:12, dimnames = list(dim1, dim2, dim3))
> arr <- array(1:12, dim = c(2, 3, 2), dimnames = list(dim1, dim2, dim3))
> arr
, , z1

   y1 y2 y3
x1  1  3  5
x2  2  4  6

, , z2

   y1 y2 y3
x1  7  9 11
x2  8 10 12

## get element
> arr[1, 3, 2]
[1] 11
> arr[1, 3,]
z1 z2 
 5 11 
> arr[1, c(1:2),]
   z1 z2
y1  1  7
y2  3  9

沒有留言:

張貼留言