year combination regression

Hi, I am a newbie in R and running a multiple regression for the following data set

Year ROA ENV1 ENV2
2012 34 12 32
2012 42 13 32
2012 34 16 33
2013 42 15 33
2013 34 16 33
2013 42 16 36
2014 42 19 36
2014 34 12 37
2014 42 19 37

Then create a table that includes R^2 values from regression.

INDEPENDENT VARIABLES ARE: EN1 AND ENV2
DEPENDENT VARIABLE IS ROA

Indpndnt(/Dpndnt 2013 2014
2012 R^2 R^2
2013 R^2 R^2

This is what I wrote, it is working somehow but the problem is I could not create such a table which shows each iterations's R^2 value, I just get final r square.

for(i in 2012:2017)
{
env1 <- ndf$EmissionsScore[ndf$Year==i]
env2 <- ndf$EnvironmentalInnovationScore[ndf$Year==i]

for(j in (i+1):2018)
{
Roa <-ndf$ROATotalAssets_Percent[ndf$Year==j]

db1= as.data.frame(cbind(Roa, env1, env2))
model <- lm (Roa ~ env1+env2, data=db1)
a<- summary(model)$r.squared
}

}

can someone help me with this?

Try this.

a <- vector("numeric",length = 21)
k <- 1
for(i in 2012:2017)
{
  env1 <- ndf$EmissionsScore[ndf$Year==i]
  env2 <- ndf$EnvironmentalInnovationScore[ndf$Year==i]
  
  for(j in i+1:2018)
  {
    Roa <-ndf$ROATotalAssets_Percent[ndf$Year==j]
    
    db1= as.data.frame(cbind(Roa, env1, env2))
    model <- lm (Roa ~ env1+env2, data=db1)
    a[k] <- summary(model)$r.squared
    k <- k + 1
  }
}
1 Like

It is working thank you very much !! I want to ask something this gives me a list, how can I create a table from this results? because I want to see which result belong to wh,ch year combination, can you please also help me with this? It is very important for me, thank you again

a <- runif(n = 21,min = 0,max = 1) # Data I invented
EnvYear <- c(rep(2012,6),rep(2013,5),rep(2014,4),rep(2015,3),
            rep(2016,2),2017)
ROAyear <- c(2013:2018,2014:2018,2015:2018,2016:2018,2017:2018,2018)
Results <- data.frame(EnvYear,ROAyear,a)
head(Results)
#>   EnvYear ROAyear         a
#> 1    2012    2013 0.5654667
#> 2    2012    2014 0.8120943
#> 3    2012    2015 0.3050359
#> 4    2012    2016 0.1563869
#> 5    2012    2017 0.2018857
#> 6    2012    2018 0.5074386
library(tidyr)
ResultsWide <- pivot_wider(Results,names_from = ROAyear,values_from = a)
ResultsWide
#> # A tibble: 6 × 7
#>   EnvYear `2013` `2014`   `2015` `2016` `2017` `2018`
#>     <dbl>  <dbl>  <dbl>    <dbl>  <dbl>  <dbl>  <dbl>
#> 1    2012  0.565  0.812  0.305    0.156  0.202  0.507
#> 2    2013 NA      0.248  0.881    0.766  0.682  0.860
#> 3    2014 NA     NA      0.00984  0.123  0.662  0.599
#> 4    2015 NA     NA     NA        0.820  0.937  0.195
#> 5    2016 NA     NA     NA       NA      0.740  0.486
#> 6    2017 NA     NA     NA       NA     NA      0.872

Created on 2022-09-18 with reprex v2.0.2

1 Like

This is exactly how I wanted!!!! I really really want to thank you, you saved my life :slight_smile: