练习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.用函数计算向量长度
> 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函数
seq(1,11,2) #from1 to11 by2
x[seq(1,11,2)]
4.用向量取子集的方法,选出除倒数第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个随机数: 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
>
思考:如何调整向量里元素的顺序?例如根据下面的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)] #根据x,调整y的顺序
[1] "A" "B" "C" "D" "E"
> #[1] "A" "B" "C" "D" "E"
> x[match(y,x)] #根据y,调整x的顺序
[1] "B" "D" "E" "A" "C"
> #[1] "B" "D" "E" "A" "C"
向量的几个进阶小问题
1.两个不同类型的向量合并在一起会怎么样?合并成一个长向量,长度为两个向量之和,数据类型,根据优先级进行转换。
> 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
还可以写成函数!
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()的接收参数可以是单个元素,也可以是向量。其次是向量按照位置索引来取子集。
4.如果向量x和y内容一致但顺序不一致,如何按照x的顺序排列y?
y[match(x,y)]