學習R記錄 <- 基礎3
向量、矩陣、陣列
向量、矩陣、陣列,都是在使用R中常用到的
1.1向量
使用c函式可以拼接數值和向量
c(1, 1:3, c(5, 8), 13)#不同值被拼接成單一向量 [1] 1 1 2 358 13
除此之外用vector函式可以建立一個指定型別和長度的向量。這個向量的值可以是0,FALSE,空的字串,等等。
> vector('numeric', 5) [1] 0 0 0 0 0 > vector('complex', 5) [1] 0+0i 0+0i 0+0i 0+0i 0+0i > vector('logical', 5) [1] FALSE FALSE FALSE FALSE FALSE > vector('character', 5) [1] "" "" "" "" ""
需要注意的是“空值”並不是NA值,空值表示為NULL。
同樣使用下面的命令與上面命令等價:
> numeric(5) [1] 0 0 0 0 0 > complex(5) [1] 0+0i 0+0i 0+0i 0+0i 0+0i > logical(5) [1] FALSE FALSE FALSE FALSE FALSE > character(5) [1] "" "" "" "" ""
1.2序列
除了冒號來建立序列之外,還有幾個更加簡單快速的函式來建立序列。
1.2.1
seq.int函式可以建立一個序列。序列的範圍有兩個數指定,原理與冒號相同。
> seq.int(3,12) [1]3456789 10 11 12
而seq.int函式比冒號方便的地方在於,它可以指定步長,
> seq.int(3,12, 2) [1]3579 11
1.2.2
seq_len函式
這個函式會建立一個從1開始到指定輸入值的序列,雖然有時候不如直接用冒號方便但是當輸入值為0時:
> 1:0 [1] 1 0 > seq_len(0) integer(0)
1.2.3
seq_along函式
此函式會建立一個從1開始,長度為輸入值的序列
> pp <- c('peter', 'piper', 'picked', 'a', 'peck', 'of', 'pickled', 'peppers') > for (i in seq_along(pp)) { + print(pp[i]) } [1] "peter" [1] "piper" [1] "picked" [1] "a" [1] "peck" [1] "of" [1] "pickled" [1] "peppers"
1.2.4 長度
每一個向量都有長度,是一個非負整數(可以為零),可以通過length 函式查詢,NA也會被計入長度。
值得一提的是字串長度,函式length 得到的是字串的數目,而每個字串中字元的長度用函式nchar 可以得到。
> sn <- c('a', 'dsad', 'dsajdsadsadas', 'fgigdfsa') > length(sn) [1] 4 > nchar(sn) [1]14 138
1.2.5 命名
R中的命名有點像python中的字典,即name=value來表示
> x <- c(apple = 1, banbana = 2, "kiwi fruit" = 3, 4) > x applebanbana kiwi fruit 1234
當然也可以在建立向量之後對其賦值。
> x <- 1:4 > names(x) <- c('apple', 'banana', "kiwi fruit") > x applebanana kiwi fruit<NA> 1234
name函式可以用來取的向量的名稱。
1.3矩陣與陣列
1.3.1 建立矩陣和陣列
使用array 函式可以建立陣列,它需要傳入兩個向量(維度和值)來作為引數。另外,可以為每個維度命名。
test <- array( 1:24, dim = c(4, 3, 2), dimnames = list( c('one', 'two', 'three', 'four'), c('ein', 'zwei', 'drei'), c('un', 'deux') ) ) > test , , un ein zwei drei one159 two2610 three3711 four4812 , , deux ein zwei drei one131721 two141822 three151923 four162024
建立矩陣類似於建立陣列,其實矩陣就是一維的陣列。
> test<- matrix( +1:24, +nrow = 4, ncol = 3, +dimnames = list( +c('one', 'two', 'three', 'four'), +c('ein', 'zwei', 'drei') +) + ) > test ein zwei drei one159 two2610 three3711 four4812
1.3.2行、列、維度
對於矩陣和陣列,dim 函式會返回其維度的整數值向量。
> dim(test) [1] 4 3 2 > dim(test) [1] 4 3
1.3.3合併矩陣
使用cbind 和rbind 兩個函式可以按 行 或者按 列 來合併矩陣。
> test1 <- matrix(seq.int(2, 24, 2), nrow = 4) > test2 <- test > cbind(test1, test2) ein zwei drei one2 10 18159 two4 12 202610 three 6 14 223711 four8 16 244812 > rbind(test1, test2) ein zwei drei 21018 41220 61422 81624 one159 two2610 three3711 four4812