问题
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.
回答1:
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"))
来源:https://stackoverflow.com/questions/38230957/r-fitting-a-model-per-subject-using-data-table-or-dplyr