Skip to content

reading long matrix

1 message · Liaw, Andy

#
Here's one possibility, if you know the number of species and the numbers of
rows and columns before hand, and the dimension for all species are the
same.

readSpeciesMap <- function(fname, nspecies, nr, nc) {
    spcnames <- character(nspecies)
    spcdata <- array(0, c(nc, nr, nspecies))
    ## open the file for reading, and close it upon exit.
    f <- file(fname, open="r")
    on.exit(close(f))
    for (i in seq(along=spcnames)) {
        ## read the name
        spcnames[i] <- readLines(f, 1)[[1]]
        ## read the grid
        spcdata[, , i] <- as.numeric(unlist(strsplit(readLines(f, nr), "")))
        ## pick up the empty line
        readLines(f, 1)
    }
    ## replace the 9s with NAs
    spcdata[spcdata == 9] <- NA
    dimnames(spcdata)[[3]] <- spcnames
    ## "transpose" the array in each species
    aperm(spcdata, c(2, 1, 3))
}

Using the example you supplied (saved in the file "species.txt"):
, ,   SPECIES1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]   NA   NA   NA    0    0    1    0   NA   NA
[2,]   NA    0    0    1    1    0    1    0   NA
[3,]    0    1    1    1    0    1    0    0    0
[4,]   NA    0    1    1    0    0    1    0    1
[5,]    1    1    0    1    0    0    0    1   NA
[6,]   NA    0    1    1    1    0    0    1   NA

, ,   SPECIES2

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]   NA   NA   NA    0    0    0    0   NA   NA
[2,]   NA    0    0    1    1    0    1    1   NA
[3,]    0    1    1    1    0    1    1    0    0
[4,]   NA    0    1    0    1    0    1    0    1
[5,]    1    1    0    0    0    0    0    1   NA
[6,]   NA    0    0    0    0    0    0    1   NA

, ,   SPECIES3

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]   NA   NA   NA    0    0    1    0   NA   NA
[2,]   NA    0    0    1    0    0    1    0   NA
[3,]    0    1    1    1    0    0    0    1    0
[4,]   NA    0    1    1    0    0    1    0    0
[5,]    1    1    0    1    0    0    0    1   NA
[6,]   NA    0    1    1    1    0    0    1   NA

Andy


From: Colin Beale