R - Fitting a model per subject using data.table or dplyr

柔情痞子 提交于 2019-12-12 02:16:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!