Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert all matrices in a list to data.frames in R

I have the output of lme function in R.

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

As you see, some elements of the output (fm2) are matrices e.g. fm2$varFix

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

like image 735
MyQ Avatar asked Dec 18 '17 08:12

MyQ


1 Answers

Maybe like this:

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, since it does not convert matrices that are in the list recursively, and attributes of elements are lost. I believe 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)
like image 153
Florian Avatar answered Oct 26 '22 04:10

Florian