Univariate linear regression (OLS)

Hi.
I am a user of Stata and I am not used to R, but I need to create a linear regression separated by years.
Can anyone help me? I put the data in here https://drive.google.com/drive/folders/1KoE0kay_mkAkn4fPHbMx3NcG6guHrp19?usp=sharing

The code in Stata is at follows:
reg interes year
reg interes edad if year==2010
est sto _mod1
reg interes edad if year==2012
est sto _mod2
reg interes edad if year==2014
est sto _mod3
reg interes edad if year==2016
est sto _mod4
reg interes edad if year==2006
est sto _modA
reg interes edad if year==2008
est sto _modB

coefplot (_mod1, label(2010)) (_mod2, label(2012))(_mod3, label(2014)) (_mod4, label(2016)), drop(?cons) xline(0) scheme(lean1) scale(0.8)
set scheme s1mono
coefplot (_modA, label(2006))(_modB, label(2008))(_mod1, label(2010)) (_mod2, label(2012))(_mod3, label(2014)) (_mod4, label(2016)), drop(?cons) xline(0) scale(0.8)

twoway lfitci interes edad
twoway lfitci interes edad, by(year)

I have tried this in R but it doesnt work:
fit<- lm(formula=interes~edad if year==2010 ,data=ESS)
summary(fit)

I can't read Stata code, but you might take an approach contained in here. The stratified models work by nesting your data into different years and fitting a model for each. The models are in individual "cells" of the data frame. We can pull the coefficient information out using the broom package and plot it up with ggplot2.

Or you could put an interaction effect in.

library(tidyverse)

# data

tibble(dat)

# stratify models?

mods = dat %>% 
  nest_by(year) %>% 
  mutate(mod = list(lm(interest ~ age, data)))

mods %>% 
  summarise(broom::tidy(mod, conf.int = T)) %>% 
  ggplot(aes(y = year, x = estimate, xmin = estimate - conf.low, xmax = estimate + conf.high)) +
  geom_pointrange() +
  facet_grid(~term, scales = "free_x")

# ... or add an interaction effect?

lm(interest ~ age * factor(year), dat)

The plot looks like this:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.