Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i add column names to my for-loop in R

I made a loop to run all possible combinations of a regression model. As i only need to keep the residuals of the model i made it as such:

df <- data.frame(t(combn(colnames(orig_df), m = 2)))

test = NULL
for (i in 1:(nrow(df)-1)) {
  for (j in (i+1):nrow(df)) {
    x <- lm(orig_df[[i]] ~ orig_df[[j]], data = orig_df)
    y <- x$residuals
    test <- cbind(test, y)
  }
}

My problem, however, is adding names to the new data frame (here named "test"). I thought a good way to tell the residuals apart would be adding x$call[2].
However if i create the loop so that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

test = NULL
for (i in 1:(nrow(df)-1)) {
  for (j in (i+1):nrow(df)) {
    x <- lm(orig_df[[i]] ~ orig_df[[j]], data = Telekom)
    y <- x$residuals
    test <- cbind(test, y)
    colnames(test) <- paste(x$call[2])  
  }
}

After this the loop stops working as it should, and the error displayed is:
length of 'dimnames' [2] not equal to array extent . What is my error here?

Thanks in advance!

For first loop:

enter image description here

For second loop:

enter image description here

>Solution :

The issue can be reproduced with mtcars data

> model <- lm(mtcars[[1]] ~ mtcars[[2]])
> model$call
lm(formula = mtcars[[1]] ~ mtcars[[2]])

We may assign the call afterwards

> model$call[[2]] <- as.formula(paste0(names(mtcars)[1], "~ ", names(mtcars)[2]))
> model$call
lm(formula = mpg ~ cyl)

In the OP’s loop, may be this modification can work

test = NULL
for (i in 1:(nrow(df)-1)) {
  for (j in (i+1):nrow(df)) {
    x <- lm(orig_df[[i]] ~ orig_df[[j]], data = Telekom)
    x$call[[2]] <- as.formula(paste0(names(orig_df)[i], "~ ", names(orig_df)[j])))
    y <- x$residuals
    test <- cbind(test, y)
    colnames(test)[ncol(test)] <- paste(x$call[[2]])  
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading