一:陣列的宣告。宣告3列(row) ✕ 2欄(column)的陣列
> a <- matrix(c(5,6,5,6,5,6), nrow=3, ncol=2)
> b <- matrix(c(7,8,7,8,7,8), nrow=3, ncol=2)
> c <- matrix(c(9,0,9,0,9,0), nrow=3, ncol=2)
> print(a)
[,1] [,2]
[1,] 5 6
[2,] 6 5
[3,] 5 6
二:陣列的合併。分成依據欄來合併(使用cbind),或是依據列來合併(使用rbind)
> l <- cbind(a,b,c)
> print(l)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 5 6 7 8 9 0
[2,] 6 5 8 7 0 9
[3,] 5 6 7 8 9 0
> m <- rbind(a,b,c)
> print(m)
[,1] [,2]
[1,] 5 6
[2,] 6 5
[3,] 5 6
[4,] 7 8
[5,] 8 7
[6,] 7 8
[7,] 9 0
[8,] 0 9
[9,] 9 0
三:對於儲存在串列裡面的陣列做合併。這時候要用到do.call這個指令
> d <- list(a, b, c)
> o <- do.call(cbind, d)
> print(o)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 5 6 7 8 9 0
[2,] 6 5 8 7 0 9
[3,] 5 6 7 8 9 0
四:陣列的合併與選取。除合併外,另使用rbind指令多加一列表示來自不同的陣列
> a <- matrix(c(5,6,5,6,5,6), nrow=3, ncol=2)
> b <- matrix(c(7,8,7,8,7,8), nrow=3, ncol=2)
> c <- matrix(c(9,0,9,0,9,0), nrow=3, ncol=2)
> a <- rbind(rep(1001, ncol(a)), a)
> b <- rbind(rep(2002, ncol(b)), b)
> c <- rbind(rep(3003, ncol(c)), c)
> e <- list(a, b, c)
> p <- do.call(cbind, e)
> p[, p[1,]==2002]
[,1] [,2]
[1,] 2002 2002
[2,] 7 8
[3,] 8 7
[4,] 7 8
> p[, p[1,]!=2002]
[,1] [,2] [,3] [,4]
[1,] 1001 1001 3003 3003
[2,] 5 6 9 0
[3,] 6 5 0 9
[4,] 5 6 9 0
五:陣列合併與刪除某些列。使用上面得到的陣列p,根據第一列選取後刪除第一列
> p[-1, p[1,]==2002]
[,1] [,2]
[1,] 7 8
[2,] 8 7
[3,] 7 8
> p[-1, p[1,]!=2002]
[,1] [,2] [,3] [,4]
[1,] 5 6 9 0
[2,] 6 5 0 9
[3,] 5 6 9 0
_EOF_
沒有留言:
張貼留言