作业1答案
练习1 下载并安装R软件
- 下载并安装R软件
- 了解R的菜单
- 安装程序包
练习2 安装并导入R程序包
- 安装程序包MASS
- 加载程序包MASS
> install.packages("MASS")
> library(MASS)
练习3 查看帮助文件
- 打开ape软件包的帮助文件
- 导入ape程序包
- 查找ape包中plot.phylo函数的帮助
- 将其中的Example文件粘贴到Console中,查看运行的结果
> help(package="ape")
> library(ape)
#example:
> x <- rtree(10)
> print(x)
Phylogenetic tree with 10 tips and 9 internal nodes.
Tip labels:
t1, t4, t10, t9, t3, t6, ...
Rooted; includes branch lengths.
> print(x, printlen = 10)
Phylogenetic tree with 10 tips and 9 internal nodes.
Tip labels:
[1] "t1" "t4" "t10" "t9" "t3" "t6" "t2" "t7" "t5" "t8"
Rooted; includes branch lengths.
> x <- rmtree(2, 10)
> print(x)
2 phylogenetic trees
> print(x, TRUE)
2 phylogenetic trees
tree 1 : 10 tips
tree 2 : 10 tips
> str(x)
Class "multiPhylo"
List of 2
$ :List of 4
..$ edge : int [1:18, 1:2] 11 12 13 14 15 15 16 16 14 13 ...
..$ tip.label : chr [1:10] "t7" "t1" "t5" "t3" ...
..$ edge.length: num [1:18] 0.231 0.56 0.224 0.955 0.521 ...
..$ Nnode : int 9
..- attr(*, "class")= chr "phylo"
..- attr(*, "order")= chr "cladewise"
$ :List of 4
..$ edge : int [1:18, 1:2] 11 12 12 11 13 14 15 15 14 13 ...
..$ tip.label : chr [1:10] "t3" "t2" "t9" "t7" ...
..$ edge.length: num [1:18] 0.537 0.477 0.962 0.283 0.275 ...
..$ Nnode : int 9
..- attr(*, "class")= chr "phylo"
..- attr(*, "order")= chr "cladewise"
练习4 查看boxplot的帮助文件
- 在控制台中输入 ?boxplot
- 查看最后的examples 将帮助文件中的examples粘贴到控制台中,运行并观看运行结果
> ?boxplot
#example:
> boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
练习5 因子生成
- 将100,200,200,200,400,600,600,600,800 输入R中,保存到numeric对象中
- 将numeric转换为factor
- 查看factor numeric的内容
> numeric <- c(100,200,200,200,400,600,600,600,800)
> numeric <- as.factor(numeric)
> numeric
[1] 100 200 200 200 400 600 600 600 800
Levels: 100 200 400 600 800
练习6 了解工作路径
- 查看当前R工作的空间目录
- 将R工作的路径设置为 d:/data/
> getwd()
> setwd("d:/data/")
练习7 编写函数实现下面功能
- 将向量a中n个数相反顺序存放
- 向量a与向量b等长,将两个向量对应位置数值交错排列,生成向量ab
f1 <- function(a){
length <- length(a)
for (i in 1:(length/2)){
b <- a[i]
a[i] <- a[length+1-i]
a[length+1-i] <- b
}
return(a)
}
f2 <- function(a,b){
length <- length(a)
ab <- c()
for (i in 1:length){
ab[2*i-1] <- a[i]
ab[2*i] <- b[i]
}
return(ab)
}