[R] Odp: Question on using elements of a vector

Petr PIKAL petr.pikal at precheza.cz
Thu Apr 8 16:37:47 CEST 2010


Hi

r-help-bounces at r-project.org napsal dne 08.04.2010 16:23:53:

> 
> Hi 
> 
> So my particular problem is this: 
> 
> I have a row vector of length 5200 elements - specifically created by 
> 
> x<-rbinom(5200,1,0.5) 
> y<-matrix(x,nrow=1,ncol=5200) 
> y 
> 
> now, each element is either a 0 or a 1 - e.g. it could be 
(0,1,1,1,1,0,0,0,1,
> 1,1) e.t.c. 
> 
> when the element is a 1, i need to multiply a number (say 1000) by 
1.005, and 
> if it is 1 again, multiply it _again_ by 1.005. 
> 
> so for example, say i have the vector (1,1). it would be 1000 X 1.005 X 
1.005 
> 
> and if the element is 0, then i need to multiply by .995 - i.e. say the 
vector
> was (1,1,0) the value would be 
> 1000 X 1.005 X 1.005 X .995. 
> 
> so my questions are these: 
> 1. how do i make R do this automatically for each element and 
> 2. as each term is multiplied, i want to graph the progress of the 
initial 1000. 

I am not sure if I understood correctly. Does this do what you want?

vec<-sample(c(0,1), 10, replace=T)
vec.2<-vec+1
1000*cumprod(c(0.995, 1.005)[vec.2]

Regards
Petr

> 
> any help would be greatly appreciated. 
> _________________________________________________________________
> New, Used, Demo, Dealer or Private? Find it at CarPoint.com.au
> 
>    [[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