CecileProust-Lima / lcmm

R package lcmm
https://CecileProust-Lima.github.io/lcmm/
58 stars 13 forks source link

Error with PredictY when model made with as.formula() #273

Closed TJRosew closed 1 month ago

TJRosew commented 2 months ago

Hi, I'm running into an error when trying to use the PredictY function with a multlcmm object that was created with formulas formed from as.formula() function. If I hard code the formulas in the multlcmm function it works fine, but I'd like to be able to programmatically form my fomulas as I'm testing a few different approaches.

An earlier verison of LCMM (or earlier version of R) was able to perform it this way without issue, but ran into this when revisiting this code to update a project. Possible there's a better way to form the formulas for use in this way.

Tested in R 4.3.1 and 4.4.1

Example code to reproduce. As far as I can tell the actual results from multlcmm are the same.

library(lcmm)

paquid$AGESCALE <- (paquid$age - 65)/10

fake_paq <- data.frame(age=(rep(seq(65,100,by=2.75),2)))
fake_paq$AGESCALE <- (fake_paq$age - 65)/10

testRLB <- multlcmm(MMSE + BVRT ~ AGESCALE, random =~AGESCALE, 
                    subject='ID', data = paquid,
                    link ="linear", verbose=FALSE,randomY = TRUE)
testRL <- multlcmm(MMSE + BVRT ~ AGESCALE, random =~AGESCALE,mixture=~AGESCALE, subject='ID', data = paquid,
                   link ="linear", verbose=FALSE,B=testRLB,ng=2,randomY = TRUE)
predmeRL <- predictY(testRL,fake_paq,var.time="AGESCALE")
## No Error

###
fixstr <- as.formula("MMSE + BVRT ~ AGESCALE")
randstr <- as.formula("~AGESCALE")

testRLSB <- multlcmm(fixstr, random =randstr, 
                     subject='ID', data = paquid,
                     link ="linear", verbose=FALSE,randomY = TRUE)
testRLS <- multlcmm(fixstr, random =randstr,mixture=randstr, 
                    subject='ID', data = paquid,
                    link ="linear", verbose=FALSE,B=testRLSB,ng=2,randomY = TRUE)
predmeRLS <- predictY(testRLS,fake_paq,var.time="AGESCALE")
### Error: Error in x$call$fixed[3] : object of type 'symbol' is not subsettable

### Alternative error if as.formula() is used within the multlcmm 
### function instead of applying it beforehand
####Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
####contrasts can be applied only to factors with 2 or more levels
VivianePhilipps commented 2 months ago

Hi,

thank you for pointing out this issue. I made some changes in the multlcmm function. Could you try it again and let me know if it now works fine ? Thanks,

Viviane

TJRosew commented 2 months ago

That seems to have resolved the issue, thank you!