rr-formula

Remove "Formula" class from formula object in R


I use the package Formula in R to create a conditional formula that can be updated.

(described here: How to update a conditional formula?)

By using the Formula package, my formula object gets two classes: "Formula" and "formula". Unfortunately, the "Formula" class does not work with the FENmlm package that I use for calculating my model. Is there a way to remove the "Formula" class and keep the "formula" class? (the "Formula" class is only needed for updating the models)

# Conditional formula
fml1 <- Formula::Formula(Petal.Width ~ Petal.Length | Species)

# Update conditional formula
fml2 <- update(fml, . ~ . + Sepal.Length)

# Class
class(fml2)
# [1] "Formula" "formula"

# Calculation
FENmlm::femlm(fml2, data = iris)
# Error in FENmlm::femlm(fml2, data = iris) : 
# The argument 'fml' must be a formula.

# Try to delete "Formula" attribute
attributes(fml2)[[1]][[1]] <- NULL
# Error in attributes(fml2)[[1]][[1]] <- NULL : replacement has length zero

Solution

  • You can update the class of the formula with class <- -

    fml1 <- Formula::Formula(Petal.Width ~ Petal.Length | Species)
    
    # Update conditional formula
    fml2 <- update(fml1, . ~ . + Sepal.Length)
    class(fml2) <- 'formula'
    
    FENmlm::femlm(fml2, data = iris)
    
    #ML estimation, family = Poisson, Dep. Var.: Petal.Width
    #Observations: 150 
    #Cluster sizes: Species: 3
    #Standard-errors type: Standard 
    #              Estimate Std. Error   z value Pr(>|z|) 
    #Petal.Length  0.150326   0.259850  0.578512 0.562919 
    #Sepal.Length -0.012575   0.227379 -0.055302 0.955898 
    #---
    #Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    #           BIC: -147.53      Pseudo-R2: 0.19402 
    #Log-likelihood:  345.17   Squared Cor.: 0.94148