[R] Sequences

Eik Vettorazzi E.Vettorazzi at uke.uni-hamburg.de
Tue Apr 7 17:52:27 CEST 2009


Hi Melissa,
first of all in R indexes of vectors starts with 1 not with 0. So 
s[0]<-0 doesn't make sense here (minor second point R is also case 
sensitive, so S[] is not the same as s[]).
Secondly rep() returns already a vector, so as.vector(s) is not necessary.
Thirdly, loops are "bad" under performance (and style ;)) aspects.
The main question remains: What do you want to calculate?!
When correcting your code it actually returns -(1:207)*mean(lambs). Is 
this intended?
You may look at ?cumsum for cumulative sums.
hth.

Melissa2k9 schrieb:
> Hi,
>
> I am trying to make a sequence and am  using a for loop for this. I want to
> start off with an initial value ie S[0]=0 then use the loop to create other
> values. This is what I have so far but I just keep getting error messages.
>
> #To calculate the culmulative sums:
>
> s<-rep(0,207)                                #as this is the length of the
> vector I know I will have
> s<-as.vector(s)
> s[0]<-0
> for (i in 1:length(lambs))                    # where lambs is a vector of
> length 207 consisting of temperature 
>                                                                     values
>
>
> {
> 	s[i]<-s[i-1]-mean(lambs)
> }
>
> I continually get the error message: 
>
> Error in s[i] <- s[i - 1] - mean(lambs) : replacement has length zero
>
>
> When I merely use s[i]<-i-mean(lambs) it works so there is obviously
> something wrong with the s[i-1] but i cant see what. All I want is for each
> S[i] to be the previous value for S - the mean!
>   

-- 
Eik Vettorazzi
Institut für Medizinische Biometrie und Epidemiologie
Universitätsklinikum Hamburg-Eppendorf

Martinistr. 52
20246 Hamburg

T ++49/40/42803-8243
F ++49/40/42803-7790




More information about the R-help mailing list