物种按照数量性状聚类并且保存为树状图

物种按照数量性状聚类并且保存为树状图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
######### Generate a simulated data set ##########

trait1 <- runif(30)*8 + 15

trait2 <- runif(30)*500 + 2300

trait3 <- runif(30)*120 + 450

dat <- data.frame(trait1, trait2, trait3)

rownames(dat) <- paste("SP", 1:30, sep = "")

##############################

###################
### Rescale (standarization and centralization) all the columns
scaled.dat <- scale(dat)

## Euclidean Distance matrix for Trait1 
dist.trait1 <- dist(scaled.dat[,1])
dist.trait2 <- dist(scaled.dat[,2])
dist.trait3 <- dist(scaled.dat[,2])
dist.traits <- dist(scaled.dat)
## Hierachical clustering of the distance matrices, using UPGMA

hclust.trait1 <- hclust(dist.trait1, method = "average")
hclust.trait2 <- hclust(dist.trait2, method = "average")
hclust.trait3 <- hclust(dist.trait3, method = "average")
hclust.traits <- hclust(dist.traits, method = "average")

#### May not be displayed properly
par(mfrow = c(2, 2))
plot(hclust.trait1 )
plot(hclust.trait2 )
plot(hclust.trait3 )
plot(hclust.traits )


## Convert the hclust into dendrograms
dendro.trait1 <- as.dendrogram(hclust.trait1)
dendro.trait2 <- as.dendrogram(hclust.trait2)
dendro.trait3 <- as.dendrogram(hclust.trait3)
dendro.traits <- as.dendrogram(hclust.traits)

#### Plot the dendrogram #########
plot(dendro.trait1, horiz = TRUE)
plot(dendro.trait2, horiz = TRUE)
plot(dendro.trait3, horiz = TRUE)
plot(dendro.traits, horiz = TRUE)


#### Using APE package to convert the dendrograms to phylo, so that the "phylo" objects can be saved as newick tree files for subsequent analysis.
library(ape)
tree.trait1 <- as.phylo(hclust.trait1)
tree.trait2 <- as.phylo(hclust.trait2)
tree.trait3 <- as.phylo(hclust.trait3)
tree.trait4 <- as.phylo(hclust.traits)


#### Save the phylogenies to disk
write.tree(tree.trait1, "tree.trait1.tre")
write.tree(tree.trait2, "tree.trait2.tre")
write.tree(tree.trait3, "tree.trait3.tre")
write.tree(tree.trait4, "tree.trait4.tre")