[R] iterative extracting data from a list without keys

arun smartpink111 at yahoo.com
Thu Mar 7 21:43:02 CET 2013


Hi,
Try this:
betas<- c(0.01,0.01,0.01)
LData<- list(int=rep(1,10), date= matrix(c(152:161,163:168,162:165),nrow=2,ncol=10,byrow=TRUE), land=c(rep(0,4),1,0,1,1,0,0))

 betas2<- c(0.01,1,2)
mapply(`*`,LData,betas2)
#$int
# [1] 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01

#$date
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#[1,]  152  153  154  155  156  157  158  159  160   161
#[2,]  163  164  165  166  167  168  162  163  164   165

#$land
# [1] 0 0 0 0 2 0 2 2 0 0


A.K.



----- Original Message -----
From: Jeff Hollenbeck <hollenb at peak.org>
To: r-help at r-project.org
Cc: 
Sent: Thursday, March 7, 2013 3:14 PM
Subject: [R] iterative extracting data from a list without keys

Dear R Users.

This seems like a simple task, but I'm stuck.

I have a list with 3 elements: (2 vectors and 1 matrix).  I wish to extract each of these data elements using index subscripts and multiply them with a vector multiplier.

What I have:
> betas
[1] 0.01 0.01 0.01

> LData[1]
$int
  [1] 1 1 1 1 1 1 1 1 1 1
$date
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] 
  [1,]  152  153  154  155  156  157  158  159  160  161  
  [2,]  163  164  165  166  167  168  162  163  164  165
$land
  [1] 0 0 0 0 1 0 1 1 0 0 

What I'm trying to do:
I would like to have the elements in the vector, betas[1:3] multiplied by corresponding data elements in LData[[1:3]].
This is how I initially try to do it, but does not work:

> probs <- betas[1:3] * LData[[1:3]]
Error in LData[[1:3]] : recursive indexing failed at level 2

Apparently, the above is not allowed.  But, if I try

> probs <- betas[1:3] * LData[1:3]
Error in betas[1:3] * LData[1:3] : 
  non-numeric argument to binary operator

I can see that the list keys get in the way of the multiplication operation.

There just has to be a way to do this.  I have searched archives and find plenty of examples of extracting data elements individually, and even extraction of multiple vector elements (unfortunately one of mine is an matrix), but not my situation.  In particular, no examples attempting to vectorize the math operation.  yapply and mapply don't seem to be what I want, but what I've read of them confuses me.  Want to avoid for loops, unless its the only way.

All help is much appreciated!

Thanks.

*******************************************************************
Jeff P. Hollenbeck
USGS Forest and Rangeland Ecosystem Science Center
3200 SW Jefferson Way
Corvallis, OR 97331
541-750-0966

    [[alternative HTML version deleted]]

______________________________________________
R-help at 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.




More information about the R-help mailing list