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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With