Search code examples
rpolynomials

How to fix the error "Subscript out of bounds"


I have a question about fixing the error:

"subscript out of bounds".

I am analyzing data of an eye-tracking experiment. You may find example data below:

Stimulus  Timebin   Language  Percentage on AOI 
1            11        L1         0.80
1            11        L2         0.60
1            12        L1         0.80
1            12        L2         0.50
1            13        L1         0.83
1            13        L2         0.50
...
10           37        L1         0.00
10           37        L2         0.50
10           38        L1         0.70
10           38        L2         0.50
10           39        L1         0.60
10           39        L2         0.70
10           40        L1         0.75
10           40        L2         0.89

...

I would like to do a Growth curve analysis with the Language and Timebin as independent variables and percentage on Area of Interest (AOI) as dependent variable. Besides, the Stimulus as random factor. I got 40 timebins for each stimulus and condition. In order to avoid the potential problem of collinearity, I want to create orthogonalized polynomials. The code below was used to create independent (orthogonal) polynomial time terms (linear, quadratic, and cubic).

Gaze_1_Poly <- poly((unique(Gaze_1$timebin)), 3)
Gaze_1[,paste("ot", 1:3, sep="")] <- Gaze_1_Poly[Gaze_1$timebin, 1:3]

I always get an error told me that there is a Out of Bounds Subscript.

Error in Gaza_1_Poly[Gaze_1$timebin, :
subscript out of bounds

So I checked the class of variables and I think it is of no problem:

   Stimulus     Timebin    Language  percentage on AOI        
"character"   "integer"    "factor"   "numeric"  

I can not figure out the reason. Can someone give me a hand?


Solution

  • See comment above. Let me know if this is what you had in mind.

    library(dplyr)
    
    Gaze_1 %>%
      left_join(data.frame(Timebin = unique(.$Timebin), poly(unique(.$Timebin), degree = 3)),
                by = 'Timebin') %>%
      setNames(c("Stimulus", "Timebin", "Language", "Percentage on AOI", "ot1", "ot2", "ot3"))