[R] Problem with a matrix

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Sat Apr 20 23:33:47 CEST 2002


"Ambrosini Alessandro" <klavan at tiscalinet.it> writes:

> I have a scattered matrix that I have to import from an external file. In
> this case all the lines could have a different size. The graph is oriented.
> I give you an example:
> a b c
> b a c d
> c b
> 
> The first row expresses that "a" has a direct path with "b" and also with
> "c".
> In the second "b" has a path with "a" and one with "c". In the third "c"
> there is a direct path with "b".
> I want to obtain the adjacency matrix.  In this case it is:
> 0 1 1 0
> 1 0 1 1
> 0 1 0 0
> 0 0 0 0
> 
> What have I to do?
> Please help me. Excuse me for my english.
[seen much worse]

Here you go:

>x <- readLines("lines.txt")
> x
[1] "a b c"   "b a c d" "c b"    
> x <- strsplit(x," ")
> x
[[1]]
[1] "a" "b" "c"

[[2]]
[1] "b" "a" "c" "d"

[[3]]
[1] "c" "b"

> x <- lapply(x,match,letters)
> x
[[1]]
[1] 1 2 3

[[2]]
[1] 2 1 3 4

[[3]]
[1] 3 2

> x <- lapply(x, function(z) cbind(z[1],z[-1]))
> x
[[1]]
     [,1] [,2]
[1,]    1    2
[2,]    1    3

[[2]]
     [,1] [,2]
[1,]    2    1
[2,]    2    3
[3,]    2    4

[[3]]
     [,1] [,2]
[1,]    3    2

> x <- do.call("rbind", x) 
> x
     [,1] [,2]
[1,]    1    2
[2,]    1    3
[3,]    2    1
[4,]    2    3
[5,]    2    4
[6,]    3    2
> m <- matrix(0,4,4)
> m[x] <- 1
> m 
     [,1] [,2] [,3] [,4]
[1,]    0    1    1    0
[2,]    1    0    1    1
[3,]    0    1    0    0
[4,]    0    0    0    0


-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list