【问题标题】:dplyr and tidyr - calculating a lot of linear models at once with factorsdplyr 和 tidyr - 使用因子一次计算大量线性模型
【发布时间】:2016-08-10 17:23:39
【问题描述】:

在阅读了 tidyverse 的更多内容后,我开始一次拟合多个线性模型,如 this 中所述。也就是说,我会按照以下方式做一些事情:

library(dplyr)
library(tidyr)
library(purrr)
df <- data.frame(y = rnorm(10), 
                 x1 = runif(10),
                 x2 = runif(10))

df %>%
  gather(covariate, value, x1:x2) %>% 
  group_by(covariate) %>% 
  nest() %>% 
  mutate(model = map(.x = data , .f = ~lm(y ~ value, data = .))) %>% 
  mutate(rsquared = map_dbl(.x = model, .f = ~summary(.)$r.squared))

问题在于,当变量不是同一类型时,这种方法会失败,例如当一个是数字而一个是因子时,因为gather() 函数会将整个value 向量强制转换为一个因子。例如,

df <- data.frame(y = rnorm(10), 
                 x1 = runif(10),
                 x3 = sample(c("a", "b", "c"), 10, replace = TRUE))

df %>%
  gather(covariate, value, x1:x3) %>% 
  sapply(class)

后面是警告

Warning message:
attributes are not identical across measure variables; they will be dropped 

          y   covariate       value 
  "numeric" "character" "character" 

value 列是一个字符,因此nest() 的技巧将不再起作用,因为所有协变量都将作为因子放入。

我想知道是否有一种 整洁 的方式来做到这一点。

【问题讨论】:

    标签: r dplyr tidyr


    【解决方案1】:

    您可以在拟合模型时转换类型,但您应该按照 cmets 中的说明小心操作,因为这可能会产生意想不到的后果。

    如果您仍想转换,您可以在整个帧上使用 readr 中的type_convert 或仅在“值”向量上使用type.convert

    使用type_convert

    mutate(model = map(.x = data , .f = ~lm(y ~ value, data = readr::type_convert(.))))
    

    使用type.convert

    mutate(model = map(.x = data , .f = ~lm(y ~ type.convert(value), data = .)))
    

    作为链的一部分,这些中的任何一个都会导致这种情况下所需的结果:

    df %>%
        gather(covariate, value, x1:x3) %>% 
        group_by(covariate) %>% 
        nest() %>% 
        mutate(model = map(.x = data , .f = ~lm(y ~ type.convert(value), data = .))) %>% 
        mutate(rsquared = map_dbl(.x = model, .f = ~summary(.)$r.squared))
    
    # A tibble: 2 x 4
      covariate              data    model   rsquared
          <chr>            <list>   <list>      <dbl>
    1        x1 <tibble [10 x 2]> <S3: lm> 0.33176960
    2        x3 <tibble [10 x 2]> <S3: lm> 0.06150498
    

    【讨论】:

    • 聪明的方法。 +1
    • 如果你碰巧有一些看起来像数字的变量,但这些变量应该被当作因子对待(这可能不是一个好主意,但确实经常发生)。 gathering 不可避免地(?)会丢失一些信息......
    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多