S. M. Niaz Arifin <niazarifin <at> yahoo.com> writes: > > Hi Experts, > I am new to R, and was wondering how to do 3D linear > regression in R. In other words, I need to Fit a > 3-Dimensional Line to Data Points (input). > > I googled before posting this, and found that it is > possible in Matlab and other commercial packages. For > example, see the Matlab link: > http://www.mathworks.com/products/statistics/demos.html?file=/products/demos/shipping/stats/orthoregdemo.html#10 > > Is there a way to achieve this in R?
As a short self-test I translated the Matlab code into R where we take as "best fit" the first principal component -- as in the Matlab example. # I copied the Matlab matrix see below; load it from there first. # X <- matrix(scan(stdin()), ncol=3, byrow=TRUE) # -0.4326 -1.0767 -0.9895 # ... # N <- nrow(X) meanX <- apply(X, 2, mean) Xpca <- princomp(X) dirVector <- Xpca$loadings[, 1] Xfit1 <- matrix(rep(meanX, each=N), ncol=3) + Xpca$score[, 1] %*% t(dirVector) t <- c(min(Xpca$score[, 1])-.2, max(Xpca$score[, 1])+.2) endpts <- rbind(meanX + t[1]*dirVector, meanX + t[2]*dirVector) library(scatterplot3d) s3d <- scatterplot3d(X[, 1], X[, 2], X[, 3], color="blue") s3d$points3d(endpts[, 1], endpts[, 2], endpts[, 3], type="l", col="red", lwd=2) I leave it as an exercise to add the straight perpendicular segment from the points to the line. You can look at it interactively applying the RGL package ! Hans Werner Borchers P.S.: Definition of X copied from the Matlab example X <- matrix(scan(stdin()), ncol=3, byrow=TRUE) -0.4326 -1.0767 -0.9895 -1.6656 0.2689 -2.7947 0.1253 0.5225 0.7053 0.2877 1.7158 -0.4033 -1.1465 0.3500 -0.6580 1.1909 -0.3924 1.0894 1.1892 0.6105 0.7931 -0.0376 -0.9963 -0.5846 0.3273 0.0463 -0.4308 0.1746 -0.0123 -0.1329 -0.1867 -0.0373 -0.9605 0.7258 -0.1663 -0.1853 -0.5883 0.9552 0.4620 2.1832 -1.3995 1.8350 -0.1364 0.3923 -1.0084 0.1139 0.9003 -0.0771 1.0668 0.9295 -0.1472 0.0593 0.5780 -0.9852 -0.0956 0.0204 -0.2554 -0.8323 0.4969 -0.0122 0.2944 0.6163 0.2148 -1.3362 -0.5177 -0.4395 0.7143 -0.2270 -0.2632 1.6236 0.0348 0.8565 -0.6918 -1.5837 -0.4571 0.8580 -0.0577 -0.2148 1.2540 0.3669 -0.0623 -1.5937 -0.0103 -0.5090 -1.4410 1.1262 -1.2071 0.5711 -0.2297 -0.0015 -0.3999 0.5307 0.1948 0.6900 0.9209 0.5309 0.8156 1.0850 -0.2560 0.7119 -0.8297 1.5774 1.2902 0.4658 1.0754 0.6686 0.3668 1.4688 1.1908 -0.7492 1.7739 -1.2025 -0.9675 -1.2144 -0.0198 1.0565 -1.0725 -0.1567 -0.1602 -0.1419 -1.6041 0.0612 -1.4099 0.2573 0.1377 -0.4227 -1.0565 -0.8339 -0.3004 1.4151 -0.2652 2.1121 -0.8051 0.2737 -1.0093 0.5287 -0.8250 -0.0866 0.2193 0.8093 -0.1305 -0.9219 0.3731 -0.2627 -2.1707 -1.2392 -1.9997 -0.0592 -0.2721 -0.8440 #EOF ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.