0

I am working in Rstudio and have a series of codes just like these. There are 34 total and I am wondering if there is an easy ways to just write it once and have it loop through the defined variable of rsqRow.a{#}, combineddfs.a{#} and internally used variables of s_{## 'State'}

# s_WA.train.lr.Summary

rsqRow.a32 = summary(s_WA.train.lr)$r.squared
# rsqRow.a32

Coef = summary(s_WA.train.lr)$coef[,1] # row, column
CoefRows = data.frame(Coef)
Pval = summary(s_WA.train.lr)$coef[,4]
PvalRows = data.frame(Pval)
combineddfs.a32 <- merge(CoefRows, PvalRows, by=0, all=TRUE)
# combineddfs.a32
# s_WI.train.lr.Summary

rsqRow.a33 = summary(s_WI.train.lr)$r.squared
# rsqRow.a33

Coef = summary(s_WI.train.lr)$coef[,1] # row, column
CoefRows = data.frame(Coef)
Pval = summary(s_WI.train.lr)$coef[,4]
PvalRows = data.frame(Pval)
combineddfs.a33 <- merge(CoefRows, PvalRows, by=0, all=TRUE)
# combineddfs.a33
# s_WY.train.lr.Summary

rsqRow.a34 = summary(s_WY.train.lr)$r.squared
# rsqRow.a34

Coef = summary(s_WY.train.lr)$coef[,1] # row, column
CoefRows = data.frame(Coef)
Pval = summary(s_WY.train.lr)$coef[,4]
PvalRows = data.frame(Pval)
combineddfs.a34 <- merge(CoefRows, PvalRows, by=0, all=TRUE)
# combineddfs.a34
Andrew Hicks
  • 376
  • 2
  • 10

1 Answers1

0

As already mentioned in comments you should get the data in a list to avoid such repetitive processes.

Find out a common pattern that represents all your dataframe names in the global environment and use that as a pattern in ls to get character vector of their names. You can then use mget to get dataframes in a list.

list_data <- mget(ls(pattern = 's_W.*train\\.lr'))

Once you have the list of dataframes, you can use lapply to iterate over it and in the function return the values that you want. Note that there might be a simpler way to write what you have in your attempt however as I don't have the data I am not going to take the risk to shorten your code. Here I am returning rsqRow and combineddfs for each dataframe. You can add/remove objects according to your preference.

all_values <- lapply(list_data, function(x) {
    rsqRow = summary(x)$r.squared
    Coef = summary(x)$coef[,1]
    CoefRows = data.frame(Coef)
    Pval = summary(x)$coef[,4]
    PvalRows = data.frame(Pval)
    combineddfs <- merge(CoefRows, PvalRows, by=0, all=TRUE)
    list(rsqRow, combineddfs)
})
Ronak Shah
  • 286,338
  • 16
  • 97
  • 143