0
Product1    Product2    Product3    Product4    Product5    Product6
434 416 759 695 930 994
228 445 487 329 219 809
364 835 229 337 830 181
203 868 167 131 138 225
897 409 565 371 519 658
832 662 154 572 383 572
168 915 115 822 215 914
450 213 215 888 251 286
250 624 429 543 129 181

R programming:

My data set contains different columns (each column is a category,above is a simulated). I want to build lm() in R linear model with all the pairs (product1 ~ product2, product2 ~ product3,and so on vice versa etc) and capture all the results of the model. Currently applied nested for loop and store the results. Is there any better way of doing this than using loops. Tried few but not much progress (struck).

newdata1 <- expand.grid(x=colnames(DF),y=colnames(DF),stringsAsFactors=FALSE)

With this got all the pairs but as I'm not very good in R not really about move forward

out<-apply(expand.grid(x=colnames(DF),y=colnames(DF),stringsAsFactors=FALSE),MARGIN = 1,function(x) lm(x~y,data=DF))

(# clearly aware the second line is incorrect,but that kind of way tried)

Any help much appreciated.

stats03
  • 1
  • 1
  • @MrFlick ,Thanks.Checked those solutions,but combination() function will not give all the pairs for eg: Product1~Product2 but not Product2~Product1 kind of cases.(results of regression is different for both these cases). Hence posted the question seeking for help.Tried expand.grid() option to get all the pairs(but struck at middle) other than loops. Thanks – stats03 Jul 05 '18 at 00:26
  • Well, if you did try something, it would be helpful to edit your question to show your code and describe exactly where you get stuck. You can use `combn` and then repeat with positions swapped. Like `rr<-combn(1:5, 2);cbind(rr, rr[nrow(xx):1,])`. – MrFlick Jul 05 '18 at 00:34
  • @MrFlick I've updated few lines of code which tried ,any help much appreciated – stats03 Jul 05 '18 at 19:44

0 Answers0