Anne-Sophie
Anne-Sophie

Reputation: 13

Problem with apply after having created a function

I want to retrieve the coefficients of linear regressions and the R squared in a table. In the first column : I have the time column and in the others the series for which I want to individually the regression with the first column.

modele <- function(data, x) {
  modele.ex <- formula(paste(colnames(data)[1],colnames(data)[2:length(data)],sep="~"))
  modele.ex
  tab <- coefficients(lm(modele.ex,data=data))
  return(data.frame(tab))
}

tab_res <- apply(data, 2, modele)

Upvotes: 0

Views: 39

Answers (1)

Adam Quek
Adam Quek

Reputation: 7163

Corrected your function to return multiple linear regression:

modele <- function(data, x)lm(formula(paste(colnames(data)[1],paste(colnames(data)[2:length(data)], collapse="+"),sep="~")), data)

mod <- modele(iris)
data.frame(t(coef(mod)), summary(mod)$r.sq)

#  X.Intercept. Sepal.Width Petal.Length Petal.Width Speciesversicolor Speciesvirginica summary.mod..r.sq
# 1     2.171266   0.4958889    0.8292439  -0.3151552         -0.723562        -1.023498         0.8673123

To regress with each individual dependent variable, it's better to write the dependent variables out as a vector first, and then write two small functions to get the models and the coef + r.sq:

dependent.variable <- colnames(iris[2:length(data)])

modele2 <- function(data, x)lm(formula(paste(colnames(data)[1], x, sep="~")), data)
output <- function(mod) data.frame(t(coef(mod)), summary(mod)$r.sq)

library(plyr)
all.mods <-lapply(dependent.variable, function(x)modele2(iris, x))
ldply(all.mods, output)

#   X.Intercept. Sepal.Width summary.mod..r.sq Petal.Length Petal.Width Speciesversicolor Speciesvirginica
# 1     6.526223  -0.2233611        0.01382265           NA          NA                NA               NA
# 2     4.306603          NA        0.75995465    0.4089223          NA                NA               NA
# 3     4.777629          NA        0.66902769           NA   0.8885803                NA               NA
# 4     5.006000          NA        0.61870573           NA          NA              0.93            1.582

Upvotes: 1

Related Questions