0

I perform linear regression on different groups (held in column grp) using weights listed down in column wght. This is working just fine.

by_time_frame <- group_by(df, grp)
weighted_model <- do(by_time_frame, tidy(lm(y~x, weights=wght, data=.)))

However, I am not able to plot the (weighted) regression line for each group on the scatter plots:

xyplot(y ~ x | grp, data=df, main='Original Data'),
       panel = function(x, y) {
           panel.xyplot(x, y)
           panel.abline(summary(weighted_model))
           }
       )

xyplot

DanY
  • 5,920
  • 1
  • 13
  • 33
user41181
  • 69
  • 3
  • Per `r` tag (hover to see): Please provide [minimal and reproducible example(s)](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5965451) along with the desired output. Use `dput()` for data and specify all non-base packages with `library()` calls. Specifically, we need sources to: `group_by`, `do`, `panel.xyplot`, `panel.abline`. Assume we run with empty, vanilla R environments. – Parfait Oct 17 '19 at 16:11
  • have you try with ggplot2 ?? – Santiago I. Hurtado Oct 17 '19 at 16:20

1 Answers1

1

Consider base R's by to build groupwise regressions:

wgt_models <- by(df, df$grp, function(sub_df) 
                    lm(y ~ x, weights = wght, data = sub_df)
              )

Then, iterate through list with for to add panel.abline layers and do so without summary():

xyplot(y ~ x | grp, data= df, main = 'Original Data'),
     panel = function(x, y) {
        panel.xyplot(x, y)
        for (m in wgt_models) panel.abline(m)
     }
)

Potentially, you can call by inside since it too is a loop, specifically apply family loop:

xyplot(y ~ x | grp, data= df, main = 'Original Data'),
     panel = function(x, y) {
        panel.xyplot(x, y)
        by(df, df$grp, function(sub_df) 
             panel.abline(lm(y ~ x, weights = wght, data = sub_df))
        )
     }
)
Parfait
  • 104,375
  • 17
  • 94
  • 125