首页 > 解决方案 > 如何从r中的函数输出自动分配给一个类

问题描述

我正在拼命尝试在 lme4::lmer 中自动化一些模型测试(因为我有太多事情要做)

我使用的函数运行一些模型并通过检查它们的统计信息找到最好的模型,然后创建res(其中有两个列表。 res$res是一个数据框

res$res$model是我需要重新运行最佳模型的文本(为了清除它,我只使用 1)

res$fits是 1 的列表,res$fits[1]是具有 13 个插槽的“正式类 'lmerMod',其名称始终与models

这是一些更有意义的代码:

models <- theBigList
## run function
res <- fit.func(models=models, response='bnParam1')
# show model selection table
res$res

# This is where you get the best model from above and put it in here to set it up for plotting.
# 
models <- res$res$model[1]

# run function
res <- fit.func(models=models, response='bnParam1')

## model selection table
res$res

# Once you get a model where the best result is the same as the "previous" one you copy and paste it in here to graph it.
# It will be the one with the the lowest CV.R2 from the 2nd 'models'  

top.fit <- res$fits$'INSERT models HERE'
#top.fit is a class lmerMod, and has the list of everything needed to be extracted and calculated to ggplot it

通常,我将最佳模型的文本复制并粘贴到显示“在此处插入模型”的空间中,但我想自动化它。

我似乎不能使用模型作为输入,也不能强制它,例如as.Classor as.String,类似的东西,也不能使用从列表中引用的其他方式。我不知道如何分配正确的变量。

编辑 #######

res$res数据框中的第一个 List 也是如此res,它将输出如下内容:

> res$res
model                       nPar      D      aic d.aic w.aic        R2     cv.R2
1 Sp + (1|Spec) + SE + TC   51 3804.244 3906.244     0     1 0.6376789 0.2586369

扩展我的最后一句话,这是最重要的。通常最后一段代码将参数传递给 lme4::fixef ,例如:

top.fit <- res$fits$"Sp + (1|Spec) + SE + TC"

这行代码有最后一部分(我之前发现但每次运行不同的分析都会改变):

models <- res$res$model[1]
> models
[1] "Sp + (1|Spec) + SE + TC"

所以我基本上想提出这样的问题top.fit <- res$fits$models,但我认为在对列表/类的引用中使用“模型”存在某种形式的类型不兼容或问题?

标签: rlistdataframeclass

解决方案


单方括号将类更改为不起作用的列表。

我通过引用双方括号解决了这个问题,这停止了转换,并将列表作为它需要的原始 lmerMod 类传递。现在我知道。

top.fit <- res$fits[[1]]


推荐阅读