首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >dplyr和tidyr -一次计算了很多线性模型。

dplyr和tidyr -一次计算了很多线性模型。
EN

Stack Overflow用户
提问于 2016-08-10 17:23:39
回答 1查看 318关注 0票数 4

在阅读了更多关于tidyverse的内容之后,我开始同时拟合许多线性模型,就像中描述的那样。也就是说,我会做一些这样的事情:

代码语言:javascript
复制
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向量强制为一个因子。例如,

代码语言:javascript
复制
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)

后面跟着警告。

代码语言:javascript
复制
Warning message:
attributes are not identical across measure variables; they will be dropped 

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

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

我想知道这样做是否有一个整洁的方法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-10 17:52:20

您可以在拟合模型时转换类型,尽管您应该按照注释中所指出的那样小心进行,因为这可能会产生意外的后果。

如果仍然想要转换,可以在整个框架上使用readr中的type_convert,也可以在“值”向量上使用type.convert

使用type_convert

代码语言:javascript
复制
mutate(model = map(.x = data , .f = ~lm(y ~ value, data = readr::type_convert(.))))

使用type.convert

代码语言:javascript
复制
mutate(model = map(.x = data , .f = ~lm(y ~ type.convert(value), data = .)))

作为链的一部分,这两种方法中的任何一种都会为这种情况带来预期的结果:

代码语言:javascript
复制
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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38879849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档