[R] Sequences
Bernardo Rangel Tura
tura at centroin.com.br
Wed Apr 8 00:44:30 CEST 2009
On Tue, 2009-04-07 at 05:16 -0700, Melissa2k9 wrote:
> 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.
Hi Melissa,
I think this is a index problem ...
your code is:
s<-rep(0,207)
s<-as.vector(s)
s[0]<-0
for (i in 1:length(lambs)){
s[i]<-s[i-1]-mean(lambs)
}
But try this code:
s<-rep(0,207)
s<-as.vector(s)
s[1]<-0 # not s[0]
for (i in 2:length(lambs)){ #not 1:length(lambs)
s[i]<-s[i-1]-mean(lambs)
}
The vector in R begin in 1 not in 0...
--
Bernardo Rangel Tura, M.D,MPH,Ph.D
National Institute of Cardiology
Brazil
More information about the R-help
mailing list