简体   繁体   English

从r的列表列中提取模型的属性

[英]extract attributes of model from a list column in r

My data is a little bit complicated.So I'm using mtcars dataset to illustrate my issue. 我的数据有点复杂,所以我使用mtcars数据集来说明我的问题。 Do lm for 4cyl car and glm otherwise. 对4cyl car做lm,否则对glm。 Save the models in a column called 'model'. 将模型保存在名为“模型”的列中。 Now I'm trying to extract the model class and put them in a different column. 现在,我尝试提取模型类,并将它们放在不同的列中。

mtcars %>% group_by(cyl) %>% 
    do (model = if (mean(.$cyl)==4) lm(mpg~wt, data=.) else glm(vs~wt, data=., family='binomial')) %>% 
    mutate(model.class=attributes(model)$class)

what I got is the error message below: 我得到的是以下错误消息:

Error in mutate_impl(.data, dots) : Column `model.type` must be length 1 (the group size), not 2

Anyone can help me with that? 有人可以帮我吗? thanks a lot. 非常感谢。

The class() function is better than delving around attributes yourself. class()函数比亲自研究属性要好。 Because an object can have more than one class, the new column needs to be a list as well. 因为一个对象可以具有多个类,所以新列也必须是一个列表。

mtcars %>% group_by(cyl) %>% mtcars %>% group_by(cyl) %>% 
    do (model = if (mean(.$cyl)==4) lm(mpg~wt, data=.) else glm(vs~wt, data=., family='binomial')) %>% 
    mutate(model.class = list(class(model)))

Here is another option to extract class information using the map function from the purrr package. 这是使用purrr包中的map函数提取class信息的另一个选项。

mtcars %>% 
  group_by(cyl) %>% 
  do (model = if (mean(.$cyl)==4) lm(mpg~wt, data=.) else glm(vs~wt, data=., family='binomial')) %>% 
  ungroup() %>%
  mutate(model.class = map(model, class))

# A tibble: 3 x 3
    cyl     model model.class
  <dbl>    <list>      <list>
1     4  <S3: lm>   <chr [1]>
2     6 <S3: glm>   <chr [2]>
3     8 <S3: glm>   <chr [2]>
Warning message:
glm.fit: fitted probabilities numerically 0 or 1 occurred 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM