qed
qed

Reputation: 23104

Dealing with transposed data in R

I have some functions like this:

myf = function(x) {
    # many similar statements involving indexing x
    do1(x[, indexfunc1()])
    do2(x[, indexfunc1()])
    do3(x[, indexfunc1()])
    do4(x[, indexfunc1()])
    do5(x[, indexfunc1()]) 
}

In all these functions, I need extract columns or rows of x, and these functions are used in some loops. The problem is sometimes we also have data in a transposed format, so this means for these data we have to get t(x). This is very ineffecient and very time consuming since these matrices are often huge.

Is there a smart way to deal with this? It would be very annoying to have to change code manually.

Upvotes: 0

Views: 90

Answers (1)

mrip
mrip

Reputation: 15163

Well, first of all, if your doX functions expect the transpose of the matrix, you are going to be calling t somewhere, for example

do1(t(x[indexfunc(),])))

So your options are:

  1. Transpose x once at the top
  2. Transpose at each doX call
  3. Rewrite your doX functions so they take an optional isTranspose argument.

Option 3 will be the most work, but also the most efficient. The situation where it would make sense to use option 2 is if x is huge, but you are only selecting a small number of rows/cols each time. In which case you could do something like this:

matrixSelect<-function(x,subset,dim=1){
  if(dim==1)
      t(x[subset,])
  else
      x[,subset]
}

and then write

myf = function(x,dim=2) {
    # many similar statements involving indexing x
    do1(matrixSelect(x,indexfunc1(),dim)
    # etc
}

Upvotes: 1

Related Questions