Created
November 14, 2011 15:21
-
-
Save seandavi/1364152 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # set up matrix | |
| x = matrix(rnorm(165*165),ncol=165) | |
| # calculate distance between all pairs and | |
| # convert to matrix | |
| df1 = as.matrix(dist(x)) | |
| # show dimensions | |
| dim(df1) | |
| # set the names of the rows and columns (convenience only) | |
| colnames(df1) <- paste("sec",1:165,sep="_") | |
| rownames(df1) <- paste("sec",1:165,sep="_") | |
| # This little function takes a dataframe or matrix | |
| # and the number of columns to retain in the output | |
| # It finds the ordering of the values in the rows | |
| # and then matches that ordering with the names from | |
| # the columns of the data frame. | |
| rows2names <- function(df,n_columns) { | |
| cnames = colnames(df) | |
| newdf = data.frame(apply(df,1,function(y) { | |
| tmp = order(y) | |
| return(cnames[tmp][1:n_columns])})) | |
| colnames(newdf) <- cnames | |
| return(t(newdf)) | |
| } | |
| # apply the function | |
| df2 = rows2names(df1,5) | |
| # note that the first column is always the | |
| # same as the row number, as we would expect | |
| head(df2) | |
| ############################################### | |
| # an alternative that takes one from the distance matrix | |
| # to a graph based on the rankings | |
| # The first step is to make a rank matrix. | |
| rankm = apply(df1,1,rank) | |
| # Now, make an adjacency matrix where two nodes | |
| # are considered "adjacent" if their rank is high | |
| # enough. The max rank is specified. | |
| maxrank = 5 | |
| adjmat = rankm < 5 | |
| library(igraph) | |
| g1 = graph.adjacency(adjmat,mode='undirected',diag=FALSE) | |
| g1 | |
| plot(g1,layout=layout.spring) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment