練習2-4
1.將基因名
"ACTR3B","ANLN","BAG1","BCL2","BIRC5","RAB","ABCT","ANLN","BAD","BCF","BARC7","BALV"
組成一個向量,賦值給x
> x <- c("ACTR3B","ANLN","BAG1","BCL2","BIRC5","RAB","ABCT","ANLN","BAD","BCF","BARC7","BALV");x
[1] "ACTR3B" "ANLN" "BAG1" "BCL2" "BIRC5" "RAB" "ABCT" "ANLN"
[9] "BAD" "BCF" "BARC7" "BALV"
>
2.用函數(shù)計算向量長度
> length(x)
[1] 12
>
3.用向量取子集的方法,選出第1,3,5,7,9,11個基因名。
> x[c(1,3,5,7,9,11)]
[1] "ACTR3B" "BAG1" "BIRC5" "ABCT" "BAD" "BARC7"
>
老師答案進階使用seq函數(shù)
seq(1,11,2) #from1 to11 by2
x[seq(1,11,2)]
4.用向量取子集的方法,選出除倒數(shù)第2個以外所有的基因名币励。
> x[-(length(x)-1)]
[1] "ACTR3B" "ANLN" "BAG1" "BCL2" "BIRC5" "RAB" "ABCT" "ANLN"
[9] "BAD" "BCF" "BALV"
>
5.用向量取子集的方法,選出出在c("ANLN", "BCL2","TP53")中有的基因名慷蠕。
> y <- c("ANLN", "BCL2","TP53")
> x%in%y
[1] FALSE TRUE FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE
> x[x%in%y]
[1] "ANLN" "BCL2" "ANLN"
>
6.修改第6個基因名為"a"并查看是否成功
> x[6] <- "a"
> x
[1] "ACTR3B" "ANLN" "BAG1" "BCL2" "BIRC5" "a" "ABCT" "ANLN"
[9] "BAD" "BCF" "BARC7" "BALV"
> x[6]
[1] "a"
>
7.生成10個隨機數(shù): rnorm(n=10,mean=0,sd=18),用向量取子集的方法食呻,篩出其中小于-2的值
> x <- rnorm(n=10,mean=0,sd=18);x
[1] 2.078207 -8.770633 2.306672 -27.461241 41.366071 -12.094710 -9.263503
[8] 11.074240 -7.115355 -6.651372
> a=c(-2)
> x[x<a]
[1] -8.770633 -27.461241 -12.094710 -9.263503 -7.115355 -6.651372
有趣的是流炕,這里使用x[x<-2] 不行,因為R識別成把2賦值給x了.
老師答案-2前加空格或(-2)
> z = rnorm(n=10,mean=0,sd=18)
> z
[1] 24.7897450 3.0518530 -20.1894157 29.1759403 -18.3319928 -44.0745443
[7] -28.1576359 0.5982541 5.8118585 3.7526579
> z[z< -2]
[1] -20.18942 -18.33199 -44.07454 -28.15764
> z[z<(-2)]
[1] -20.18942 -18.33199 -44.07454 -28.15764
>
思考:如何調整向量里元素的順序搁进?例如根據(jù)下面的x生成BDEAC
x <- c("A","B","C","D","E");x
> x <- c("A","B","C","D","E");x
[1] "A" "B" "C" "D" "E"
> x[c(2,4,5,1,3)]
[1] "B" "D" "E" "A" "C"
>
難點--向量匹配排序:match
> x <- c("A","B","C","D","E")
> y <- c("B","D","E","A","C")
> match(x,y) x元素在y中的位置
[1] 4 1 5 2 3
> y[match(x,y)] #根據(jù)x浪感,調整y的順序
[1] "A" "B" "C" "D" "E"
> #[1] "A" "B" "C" "D" "E"
> x[match(y,x)] #根據(jù)y,調整x的順序
[1] "B" "D" "E" "A" "C"
> #[1] "B" "D" "E" "A" "C"
向量的幾個進階小問題
1.兩個不同類型的向量合并在一起會怎么樣饼问?合并成一個長向量影兽,長度為兩個向量之和,數(shù)據(jù)類型莱革,根據(jù)優(yōu)先級進行轉換峻堰。
> x <- c(1,2,4,5,6)
> y <- c("a","b","d")
> test <- c(x,y)
> test
[1] "1" "2" "4" "5" "6" "a" "b" "d"
> x=c(3,x)
> x=c(x,4)
> x
[1] 3 1 2 4 5 6 4
>
2.如何將兩個向量合到一起,組成一個長向量盅视?以上代碼
3.如何在向量首/尾/中間某位置增加一個元素捐名?
n=3
x=c(1,3,5,8,6)
x
## [1] 1 3 5 8 6
y=c(x[1:n-1],7,x[n:length(x)])
y
## [1] 1 3 7 5 8
還可以寫成函數(shù)!
join <- function(x,n,y){
c(x[1:n-1],y,x[n:length(x)])
}
x=c(1,3,5,8,6)
join(x,3,7)
## [1] 1 3 7 5 8 6
前三個題的中心思想是c()的接收參數(shù)可以是單個元素闹击,也可以是向量镶蹋。其次是向量按照位置索引來取子集。
4.如果向量x和y內容一致但順序不一致,如何按照x的順序排列y贺归?
y[match(x,y)]