On Tue, 2005-07-12 at 14:37 -0300, Rogério Rosa da Silva wrote:
> Dear list,
> 
> I will like to learn how to read a lower triangular matrix in R. The
> input file *.txt have the following format:
> 
>      A   B   C   D   E
> A   0   
> B   1    0
> C   2    5    0   
> D   3    6    8    0  
> E   4    7    9   10    0
> 
> 
> How this can be done?
> 
> Thanks in advance for your help
> 
> Rogério


I don't know that this is the easiest way of doing it, but here is one
approach:

# I saved your data above in a file called "test.txt"

# Read the first line of test.txt to get the colnames as chars
col.names <- unlist(read.table("test.txt", nrow = 1, as.is = TRUE))

# now read the rest of the file using 'fill = TRUE' to pad lines
# with NAs 
# skip the first line
# set the row.names as the first column in the text file
# coerce to a matrix
df <- as.matrix(read.table("test.txt", fill = TRUE, skip = 1, 
                row.names = 1))

# Now set the colnames of df
colnames(df) <- col.names

> df
  A  B  C  D  E
A 0 NA NA NA NA
B 1  0 NA NA NA
C 2  5  0 NA NA
D 3  6  8  0 NA
E 4  7  9 10  0

If you should further want to set the diagonal to NA:

> diag(df) <- NA

> df
   A  B  C  D  E
A NA NA NA NA NA
B  1 NA NA NA NA
C  2  5 NA NA NA
D  3  6  8 NA NA
E  4  7  9 10 NA


See ?read.table for more information on the file reading part.

HTH,

Marc Schwartz

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Reply via email to