r - 当我需要为每个元素选择适当的模型时,如何避免 for 循环?

标签 r for-loop

我有一个包含一些模型的数据框,我想将适当的模型应用于不同数据框的每一行,然后将模型的预测值添加到该数据框的新列中

我有一个相当不优雅的解决方案,使用 for 循环,并要求我对模型所应用的数据帧进行排序。

# sort my sample data (mtcars) by cylinder, so the final data lines up
mycars <- mtcars[order(mtcars$cyl),] 

# build a linear model for each number of cylinders,
# estimating mpg from displacement
by_cyl <- group_by(mycars, cyl)
models <- by_cyl %>% do(mod = lm(mpg ~ disp, data = .))

# my inelegant solution for adding the predicted mpg into the dataset
prediction <-  c()
for (i in models$cyl){
  temp <- filter(mycars, cyl == i)
  prediction <- c(prediction, predict((models %>% filter(cyl==i))$mod[[1]], temp)) 
}
mycars$mpg.pred <- prediction

我希望能够避免使用 for 循环,并且如果可能的话也将源日期保留其原始顺序

最佳答案

使用 tidyverse,其中 .fitted 是预测值:

library(tidyverse)

mtcars %>% 
  nest(-cyl) %>% 
  mutate(mod = map(data, ~lm(mpg ~ disp, data = .))) %>% 
  mutate(pred = map(mod, broom::augment)) %>% 
  select(pred) %>% 
  unnest()
#> # A tibble: 32 x 8
#>      mpg  disp .fitted  .resid .std.resid   .hat .sigma .cooksd
#>    <dbl> <dbl>   <dbl>   <dbl>      <dbl>  <dbl>  <dbl>   <dbl>
#>  1  21    160     19.7 -1.34       0.944  0.195    1.61 0.108  
#>  2  21    160     19.7 -1.34       0.944  0.195    1.61 0.108  
#>  3  21.4  258     20.0 -1.39       1.55   0.681    1.28 2.57   
#>  4  18.1  225     19.9  1.79      -1.36   0.311    1.40 0.419  
#>  5  19.2  168.    19.7  0.486     -0.336  0.167    1.75 0.0113 
#>  6  17.8  168.    19.7  1.89      -1.30   0.167    1.44 0.170  
#>  7  19.7  145     19.6 -0.0953     0.0711 0.284    1.77 0.00101
#>  8  22.8  108     26.3  3.48      -1.29   0.0920   2.70 0.0849 
#>  9  24.4  147.    21.0 -3.35       1.45   0.330    2.62 0.521  
#> 10  22.8  141.    21.8 -0.956      0.396  0.267    2.96 0.0286 
#> # ... with 22 more rows

reprex package于2019-06-18创建(v0.3.0)

关于r - 当我需要为每个元素选择适当的模型时,如何避免 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56654491/

相关文章:

java - 在 Java 中,一秒钟需要多长时间?测量 Java 中的延迟时间

r - 具有多个条件的 for 循环的向量化

r - R中组中的ifelse函数组

r - 我如何通过 R Dataframe 中的向量

Javascript for循环直到 - 多个条件

javascript - 在分配之前使用变量 'value'

python - 创建字符串行,其中行数等于列表中的元素数

r - 对矩阵列表求和

r - 在 ubuntu 20.04 中安装 R

r - 如何根据 r 中的分隔符和/或位置将一列拆分为三列