# [R] Reading in data in a triangle

Liaw, Andy andy_liaw at merck.com
Mon Oct 8 19:58:28 CEST 2001

```> 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
> >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

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

```