[R] reading in a tricky computer program output

Berwin A Turlach berwin at maths.uwa.edu.au
Sun Feb 5 10:14:12 CET 2006


>>>>> "BAT" == Berwin A Turlach <berwin at maths.uwa.edu.au> writes:

>>>>> "TM" == Taka Matzmoto <sell_mirage_ne at hotmail.com> writes:

    TM> and then assign the character vector to the numeric vector by

    TM> names<-first.10
    TM> first.10 = numeric.vector
    TM> combined.one <- cbind(names,first.10)
    TM> container <- diag(10)
    TM> for (i in 1:(10*10))
    BAT> I don't really understand this loop.  If I reverse-engineer this code
    BAT> correctly thenthe matrix `combined.one' is not a 2*100 matrix, so you
    BAT> should get an error while exectuting this loop.
This should have been:  ... `combined.one' is not a 100*2 matrix ...

    TM> Is there any other neat way to do this?
    BAT> Neat way to create those character vectors?  Or a neat way to read in
    BAT> the data from a file?

    BAT> If the latter, I would use the following code:
Before somebody else points out the obvious optimisation of my code,
here is a (slightly) improved version of the function

      matzmoto <- function(file, diag=TRUE){
      
        dat <- scan(file)
        nn <- nvar <- sqrt(2*length(dat)+0.25) - 0.5
        if(!diag){
          nvar <- nvar + 1
        }
        res <- matrix(0,nvar,nvar)
        ind <- upper.tri(res, diag=diag)
      
        rind <- 1:5
        while(nn > 0){
          if( nn < 5 ){
            rind <- rind[1:nn]
          }
      
          how.many <- sum(ind[rind,])
          res[rind,][ind[rind,]] <- dat[1:how.many]
          
          dat <- dat[-(1:how.many)]
      
          rind <- rind + 5
          nn <- nn - 5
        }
        t(res)
      }

Cheers,

        Berwin




More information about the R-help mailing list