R - 使用data.table或dplyr为每个主题拟合模型 [英] R - Fitting a model per subject using data.table or dplyr
问题描述
我有许多主题的一组观察,我想为每个主题拟合一个模型。
Im使用包 data.table
和 fitdistrplus
,但也可以尝试使用 dlpyr
p>
说我的数据是这种形式:
#subject_id #observation
1 35
1 38
2 44
2 49
这里是我到目前为止尝试:
subject_models< - dt [,fitdist(observation,norm, method =mme),by = subject_id]
这会导致一个错误, fitdist
返回不能存储在datatable / dataframe中的 fitdist
对象。
有没有任何直观的方法使用 data.table
或 dplyr
? / p>
EDIT:提供了一个dplyr答案,但我也赞赏一个data.table,我会尝试运行一些基准这两个。
这可以很容易地用 purrr
我假设它与@alista建议的相同。
purrr)
库(dplyr)
库(fitdistrplus)
dt%>%split(dt $ subject_id)%>%map(〜fitdist method =mme))
或者,不带 purrr
,
dt%>%split(dt $ subject_id)%>%lapply )fitdist(x $ observation,norm,method =mme))
I have a set of observations for many subjects and I would like to fit a model for each subject.
I"m using the packages data.table
and fitdistrplus
, but could also try to use dlpyr
.
Say my data are of this form:
#subject_id #observation
1 35
1 38
2 44
2 49
Here's what I've tried so far:
subject_models <- dt[,fitdist(observation, "norm", method = "mme"), by=subject_id]
This causes an error I think because the call to fitdist
returns a fitdist
object which is not possible to store in a datatable/dataframe.
Is there any intuitive way to do this using data.table
or dplyr
?
EDIT: A dplyr answer was provided, but I would appreciate a data.table one as well, I'll try to run some benchmarks against the two.
This can be easily achieved with the purrr
package
I assume its the same thing @alistaire suggested
library(purrr)
library(dplyr)
library(fitdistrplus)
dt %>% split(dt$subject_id) %>% map( ~ fitdist(.$observation, "norm", method = "mme"))
Alternatively, without purrr
,
dt %>% split(dt$subject_id) %>% lapply(., function(x) fitdist(x$observation, "norm", method = "mme"))
这篇关于R - 使用data.table或dplyr为每个主题拟合模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!