Convert all matrices to list in data.frames in R

I have function output lmein R.

library(nlme)
fm2 <- lme(distance ~ age + Sex, data = Orthodont, random = ~ 1)
str(fm2)

As you can see, some output elements ( fm2) are matrices, for example.fm2$varFix

I am looking for a function to take an object and convert all submatrices to data.frames.

+6
source share
1 answer

Maybe so:

lapply(fm2, function(x) {if(any(class(x)=="matrix")) as.data.frame(x) else x})

EDIT: although this answer has already been accepted, I was not happy with the solution, because it does not convert the matrices in the list recursively, and the attributes of the elements are lost. I believe that the following solution solves both problems:

library(nlme)
fm2 <- lme(distance ~ age + Sex, data = Orthodont, random = ~ 1)
str(fm2)

replace_sub_dataframes <- function(x)
{
  if(any(class(x)=="list"))
  {
    x_copy = x
    attrs = setdiff(names(attributes(x)),"names")
    x = lapply(x,replace_sub_dataframes)
    if(length(attrs)>0)
    {
      for(i in 1:length(attrs))
      {
        attr(x,attrs[i]) <- replace_sub_dataframes(attr(x_copy,attrs[i]))
      }
    }
    return(x)
  }
  else
  {
    if(any(class(x)=="matrix")) 
      return(as.data.frame(x)) 
    else 
      return(x)
  }
}

fm3 = lapply(fm2, replace_sub_dataframes)
+6
source

All Articles