Saikiran Yerram
Saikiran Yerram

Reputation: 3092

subscripting not working in R

I have this simple code and it is driving me nuts. The code is simply looping through a vector and subscripting parts of it.

preda <- function(d, k) {
  n <- length(d)
  cat("Length: ", n, "Loop:", k+1, "-", n, "\n")
  for(i in seq(from=k+1, to=n, by=1)) {
    cat("Index: ", i, "; Subscript Start: ", i-k, "; End: ", i-1, "\n")
    cat("Value: ", d[i-k:i-1], "\n") # on first loop, this should do 1:3
  }
}

The output

> X = sample(0:1,100,replace=T)
> preda(X, 3)
  Length:  100 Loop: 4 - 100
  Index:  4; Subscript Start:  1 End:  3
  #it doesn't subscript here.
  Value:  0 0 1 0 1 1 0 1 0 1 1 1 0 0 1 0 1 1 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 1 1 1 0 1 1 1 1 0 0 0 1 1 1 0 0 0 0 0 1 0 0 0 1 1 0 1 0 0 0 1 0 0 0 0 1 0 1 1 0 0 0 0 0 1 0 1 0 1 1 0 0 1 0 1 1 0 0 1 1 1 1 1 0 0
  Index:  5 St:  2 En:  4
  Error in d[i - k:i - 1] : only 0's may be mixed with negative subscripts

What am I missing?

Upvotes: 0

Views: 61

Answers (1)

erasmortg
erasmortg

Reputation: 3278

It seems that you are having problems with the colon operator (:). Swithcing to d[(i-k):(i-1)] will solve the issue:

#> preda(X,3)
#Length:  100 Loop: 4 - 100 
#Index:  4 ; Subscript Start:  1 ; End:  3 
#Value:  0 0 0 
#Index:  5 ; Subscript Start:  2 ; End:  4 
#Value:  0 0 1 
#...

Remember that the colon operator (see help(":")) needs two arguments (a and b) so a parenthesis will keep things tidy.

Upvotes: 2

Related Questions