【问题标题】:alternative to broom::tidy?扫帚的替代品::整洁?
【发布时间】:2021-11-08 05:20:34
【问题描述】:

在我的分析代码中,我一直使用broom::tidy 来提取数据框中每组的回归斜率:

E1.first_trial_df <- data.frame( 
  search_type  = factor(rep(1:3, each = 10)),
  set_size    = rep(1:10,3),
  RT     = runif(300, min = 0, max = 2500)
)

E1.search_slopes_first_trial <- E1.first_trial_df %>%
  group_by(search_type) %>%
  do(model=lm(RT~set_size,data=.)) %>%
  broom::tidy(model) %>%
  filter(term=='set_size')

我在使用 R 时遇到了问题,所以我重新安装了 R、Rstudio 和我的所有软件包,我猜我已经升级到新版本的扫帚了。所以我现在收到以下错误消息:

var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) 中的错误: 对因子 x 调用 var(x) 已失效。 使用类似 'all(duplicated(x)[-1L])' 的东西来测试一个常数向量。 另外:警告信息: 1:不推荐使用数据框整理器,并将在即将发布的 broom 中删除。 2:在 mean.default(X[[i]], ...) 中: 参数不是数字或逻辑:返回 NA 3:在 mean.default(X[[i]], ...) 中: 参数不是数字或逻辑:返回 NA

知道这里发生了什么,以及如何解决它吗? 谢谢!

【问题讨论】:

  • 是的,它以前工作过!
  • 我以前不知道,但是tidy.data.frame 对它的... arg 没有任何作用,所以你的model 值没有被使用。

标签: r tidyverse broom


【解决方案1】:

使用base 包替代tidyr

df = E1.first_trial_df
df$search_type = as.factor(df$search_type)
#Splitting data frame 
df = split(df, df$search_type)

#Using `lm` to fit the model
lmr = lapply(df, function(x){
  lmr = lm(x$RT ~ x$set_size, x)
})

#Extract regression co-efficient for each model
rslope = lapply(lmr, function(x) x[["coefficients"]][["(Intercept)"]])
rslope = unlist(rslope)
#Extract intercept for each model
intercept = lapply(lmr, function(x) x[["coefficients"]][["x$set_size"]])
intercept = unlist(intercept)

【讨论】:

    【解决方案2】:

    您可以通过以下方式修改您的代码:

    library(tidyverse)
    library(broom)
    
    E1.first_trial_df %>%
      group_by(search_type) %>%
      nest() %>%
      mutate(model = map(data, ~ lm(RT ~ set_size, data = .x)), 
             tidy = map(model, ~ tidy(.x))) %>%
      unnest(tidy) %>%
      filter(term == 'set_size') %>%
      select(!c(data, model))
    
    # A tibble: 3 x 6
    # Groups:   search_type [3]
      search_type term     estimate std.error statistic p.value
      <fct>       <chr>       <dbl>     <dbl>     <dbl>   <dbl>
    1 1           set_size   -0.898      23.9   -0.0376   0.970
    2 2           set_size  -27.0        24.4   -1.11     0.271
    3 3           set_size   -2.00       26.0   -0.0768   0.939
    

    【讨论】:

    • 谢谢!知道为什么他们不再支持我在原始版本中使用的功能了吗?
    • 不客气,很遗憾我不知道,但也许你可以在这里找到问题的答案:github.com/amices/mice/issues/274
    猜你喜欢
    • 1970-01-01
    • 2021-06-25
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    相关资源
    最近更新 更多