Skip to content
Prev 73502 / 398500 Next

simple question: reading lower triangular matrix

On Tue, 2005-07-12 at 14:37 -0300, RogÃ©rio Rosa da Silva wrote:
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
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:
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