On Feb 4, 2010, at 11:53 PM, Carrie Li wrote:

Thank you, David
Here is an example :


Z=matrix(rnorm(20), nrow=4)
index=replicate(4, sample(1:5, 3))
P=4
tmpr=list()
for (i in 1:P)
{
  tmp = Z[i,index[,i]]
  tmpr[[i]]=tmp
}


So, I am trying to pull out the values in Z for each row, but now I only want to pull out the values indexed by the matrix "index"
And, since I have large P, so I would like to avoid loop.

My understanding (subject to correction):
the notion that loops are inefficient for this sort of activity is a misconception. If your count of desired elements to be extracted from Z are always the same, then a loop is probably reasonably efficient.

You could accelerate the process by not making an assignment to the intermediate 'tmp"

 for (i in 1:P) { tmpr[[i]]  <-  Z[i,index[,i]] }


-- David.

Any quick way to do this ?

Thanks again!!

Carrie






On Thu, Feb 4, 2010 at 10:39 PM, David Winsemius <dwinsem...@comcast.net > wrote:

On Feb 4, 2010, at 9:51 PM, Carrie Li wrote:

Dear R-helpers ,

I have a simple loop as follows, however, to be more efficient, I would like
to use any apply functions (tapply, I suppose)
But how can I do this ? I am not very clear about this.

# Z is a P * Q matrix
# so for each row of Z, I would like to pull out only some of the elements,
and save as a separate matrix under a list
# index is a vector with length smaller than Q, but the index could be
different for each row of Z.

An example would help. Sounds like you need a list structure to hold the index and I don't see that you have constructed one.


for (i in 1:P)
{
 tmp = matrix(Z[i, index], nrow=1)

Seems as though you would need to "index" in a verb sense (with "i") the index (in a noun sense) structure. Might be better to call it "idx".
Perhaos

tmp = matrix(Z[i, index[[i]] ], nrow=1) # the nrow=1 appears superfluous


 tmpr[[i]]=tmp
}


any help is highly appreciated!!

Thank you all

Carrie

       [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT



David Winsemius, MD
Heritage Laboratories
West Hartford, CT

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to