0

Is it possible to evaluate the result of a function that returns a different number of rows eg Lag() inside a linear model?

This error seems to suggest that because Lag returns NA for the first value the number of rows is incorrect. Lag(csv$Shame) has 2 rows while the rest of the dataset has 3.

> Lag(csv$Shame)
     Lag.1
[1,]    NA
[2,]     4
[3,]     5

Example:

csv<-data.frame(SelfEsteem=c(1,2,3),Shame=c(4,5,6),participant_number=c(1,1,1))
csv$laggedShame<-Lag(csv$Shame)

works<-lme(SelfEsteem~1,random=~laggedShame|participant_number,na.action=na.omit,data=csv)
fails<-lme(SelfEsteem~1,random=~Lag(Shame)|participant_number,na.action=na.omit,data=csv)

Error in lme.formula(SelfEsteem ~ 1, random = ~Lag(Shame) | participant_number,  : 
  nlminb problem, convergence error code = 1
  message = false convergence (8)
In addition: Warning message:
In matrix(unlist(value), nrow = nrow(data), dimnames = list(row.names(data),  :
  data length [4] is not a sub-multiple or multiple of the number of rows [3]

This question shares a similar title with: this post but the error is completely different

Community
  • 1
  • 1
Rilcon42
  • 9,584
  • 18
  • 83
  • 167

1 Answers1

0

I think its because you aren't actually removing the NAs from the csv data.frame. You could try just creating the data.frame from works in the function itself then using a similar code as in works. I think this is what you want:

library(data.table)
fails<-lme(SelfEsteem~1,random=~LShame|participant_number,na.action=na.omit,data=cbind(csv,LShame=shift(csv$Shame,1L,type="lag")))
Mike H.
  • 13,960
  • 2
  • 29
  • 39