# [R] Reading in data in a triangle

John Fox jfox at mcmaster.ca
Mon Oct 8 20:58:51 CEST 2001

Dear Andy and Stuart,

Once you've read the elements in the lower triangle, it's easy to compute
the order of the matrix. If the order is n, then the number of elements in
the lower triangle is k = n * (n + 1)/2, from which n = (sqrt(1 + 8 * k) -
1)/2.

Thus,

> elements <- scan('c:/temp/LT.txt')
> n <- (sqrt(1 + 8 * length(elements)) - 1)/2
> U <- matrix(0, n, n)
> U[outer(1:n, 1:n, '<=')] <- elements
> t(U)
[,1] [,2] [,3] [,4]
[1,]    1    0    0    0
[2,]    2    3    0    0
[3,]    4    5    6    0
[4,]    7    8    9   10
>

John

At 01:58 PM 08/10/2001 -0400, Liaw, Andy wrote:
> > Dear Stuart,
> >
> > At 03:16 PM 05/10/2001 -0500, s-luppescu at uchicago.edu wrote:
> > >I have plain-text data in lower triangular form that I want
> > to read in. Does
> > >anyone know of an easy way to do this?
> >
> > It's not altogether clear to me what you want to do, but I'll
> > take a stab
> > at it.
> >
> > Simply to read the data into a vector is no trick: scan will do that.
> > Assuming that you want to read the data into a
> > lower-triangular matrix, you
> > might try something like the following, starting with the
> > file LT.txt,
> > which contains:
> >
> >      1
> >      2 3
> >      4 5 6
> >      7 8 9 10
> >
> > Then, constructing an upper-triangular matrix and transposing it,
> >
> >      > U <- matrix(0, 4, 4)
> >      > U[outer(1:4, 1:4, '<=')] <- scan('c:/temp/LT.txt')
> >      > t(U)
> >          [,1] [,2] [,3] [,4]
> >      [1,]    1    0    0    0
> >      [2,]    2    3    0    0
> >      [3,]    4    5    6    0
> >      [4,]    7    8    9   10
> >
> > Is that what you need?
> >
> >   John
> >
>
>John's solution requires the dimension of the matrix be known beforehand.
>Here's a slightly more general way, using connections.  Maybe others can
>improve on it?
>
>lucon <- file("LU.txt", open="rt")
>close(lucon)
>n <- length(x)
>U <- matrix(0, n, n)
>U[upper.tri(U, diag=TRUE)] <- as.numeric(unlist(strsplit(x, " ")))
>U <- t(U)
>
>
>Andy

-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._