Showing fitted values with R and dplyr

こ雲淡風輕ζ 提交于 2019-12-01 08:33:58
Medical physicist

I found an easy solution based on this question dplyr::do() requires named function?

Fit <-  DF %>%
    group_by(Channel) %>% 
    do({
        fit = lm(mean ~ Col + poly(Row, 2), data = .)
        pred <- predict(fit)
        data.frame(., pred)
    })

If you could have provided more fields apart from Channel, Col and Row we would have given better direction. Right now, I have prepared solution for given Channel & Col. You can always add Row and define lm using other fields you have.

I think following should work for you,

library(dplyr)
df = data.frame(Channel=c(rep(0,50),rep(1,50),rep(2,100)), 
                Row = 1:200, 
                Col = c(rep(1,50),rep(2,100),rep(3,50)), 
                mean = rnorm(200))
glimpse(df)
Fit <-  df %>%
  group_by(Channel,Col) %>% 
  do(fit = lm(mean ~ poly(Row, 2), data = .))
Fit    
Source: local data frame [4 x 3]
Groups: <by row>    
  Channel Col     fit
1       0   1 <S3:lm>
2       1   2 <S3:lm>
3       2   2 <S3:lm>
4       2   3 <S3:lm>
Fit$fit
[[1]]    
Call:
lm(formula = mean ~ poly(Row, 2), data = .)    
Coefficients:
  (Intercept)  poly(Row, 2)1  poly(Row, 2)2  
       0.1403         0.2171        -0.6281
[[2]]    
Call:
lm(formula = mean ~ poly(Row, 2), data = .)
Coefficients:
  (Intercept)  poly(Row, 2)1  poly(Row, 2)2  
     -0.07416       -0.39332        0.57889
[[3]]
Call:
lm(formula = mean ~ poly(Row, 2), data = .)
Coefficients:
  (Intercept)  poly(Row, 2)1  poly(Row, 2)2  
       0.1349        -0.3405         1.5679
[[4]]
Call:
lm(formula = mean ~ poly(Row, 2), data = .)
Coefficients:
  (Intercept)  poly(Row, 2)1  poly(Row, 2)2  
       0.0379         1.2867        -1.1028
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!