Question: how to create a minimun spanning tree with R
0
gravatar for Lila M
3.3 years ago by
Lila M 460
UK
Lila M 460 wrote:

'm trying to create a minimun spanning tree with R. My problem is that I have my distances stored in a txt as follow:

PID1  PID2 distance
1      4     0.002
2      5     0.004
3      6     0.003

Does exist anyway in which I can use my txt as matrix? I tried to transform it but I couldnt. Thank you everyone in advance

My code:

dat=read.table("distances.txt", dec='.', header=T)

Matrix<- as.matrix(dat) 

mstree <-mst(Matrix)

Error en [<-(*tmp*, j, index.i, value = 139127) : 

 

 

tree minimun spanning tree R • 1.6k views
ADD COMMENTlink modified 2.1 years ago by Biostar ♦♦ 20 • written 3.3 years ago by Lila M 460

This is not a bioinformatics question but an R programming one. You may have better luck getting an answer on StackOverflow.
First issue is that your data file is not in matrix form. as.matrix() is not going to do any rearranging, it just converts internal data types. Second, mstree() (from the spdep package) doesn't take a matrix as argument. Read the docs.
Finally, for graph-related work in R, I suggest using the igraph package.

ADD REPLYlink written 3.3 years ago by Jean-Karim Heriche18k

I guess Lila M is using mst() from {ape} package, and it may take a matrix as argument.  

ADD REPLYlink written 3.3 years ago by h.mon23k
0
gravatar for h.mon
3.3 years ago by
h.mon23k
Brazil
h.mon23k wrote:

In R, "?mst" will display the help of the function. If you read the help of mst(), and then follow to the help of dist(), you will find out the particular matrix format the mst() function expects:

         P1            P2    ...        Pn

P1       0            0.002           d(1,n)

P2     0.002            0             d(2,n)

...

Pn     d(1,n)         d(2,n)             0

You are mixing the R data of type matrix with the particular matrix mst() expects. You will have a bit more of work to convert your data to a matrix of distances.

ADD COMMENTlink written 3.3 years ago by h.mon23k
0
gravatar for rmf
3.3 years ago by
rmf540
rmf540 wrote:
#load package
library(reshape2) #dcast() #reformatting table
library(fossil) #dino.mst() #mst function

#create a data frame with coordinates x and y and distance
dat <- data.frame(x=c(1,1,1,1,2,2,2,3,3,4),
                  y=c(1,2,3,4,2,3,4,3,4,4),
                  distance=c(0,0.2,0.5,0.1,0,0.5,0.8,0,0.1,0))
#convert to wide format
x <- dcast(dat,y~x,value.var="distance")
#remove first column
x <- x[,-1]
#convert to a dist object
x <- as.dist(x)
#this dist object can be used in any function that accepts a dist object.

#calculate mst
mstobj <- dino.mst(x)
ADD COMMENTlink written 3.3 years ago by rmf540
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1762 users visited in the last hour