Skip to content

Instantly share code, notes, and snippets.

@aammd
Last active December 16, 2016 12:22
Show Gist options
  • Save aammd/591e382edc470fca650eb051fd3ecaba to your computer and use it in GitHub Desktop.
Save aammd/591e382edc470fca650eb051fd3ecaba to your computer and use it in GitHub Desktop.
microbenchmark::microbenchmark({lm(ys~xs, data = testdf)$residuals},
{fastLm(ys~xs, data = testdf)$residuals},
{homemade_residuals(indeps, deps)}, times = 500)
identical(homemade_residuals(indeps, deps), homemade_residuals2(indeps, deps))
# all.equal()
testdf <- data_frame(xs = runif(200, 0, 15),
ys = xs * 5 + 15 + rnorm(200, sd = 3))
profvis::profvis({homemade_residuals(testdf)})
@vanderleidebastiani
Copy link

vanderleidebastiani commented Dec 13, 2016

X<-matrix(rnorm(30),10,3)
Y<-matrix(rnorm(5000),10,50)

	pro.residuals0<-function(x,scoresofz){
		res<-matrix(NA,dim(x)[1],dim(x)[2])
		for(i in 1:dim(x)[2]){ 
			res[,i]<-cbind(stats::residuals(stats::lm(V1~.,data=as.data.frame(cbind(x[,i],scoresofz)))))
		}
	return(res)
	}

	pro.residuals1<-function(Y,X){
		X<-base::scale(X, scale = FALSE)
		Y<-base::scale(Y, scale = FALSE)
		Yfit<-X%*%solve(t(X)%*%X)%*%(t(X))%*%Y
		Yres<-Y-Yfit
	return(Yres)
	}

	pro.residuals2 <- function(Y, X){
		res<-matrix(NA,dim(Y)[1],dim(Y)[2])
		for(i in 1:dim(Y)[2]){
			mat <- cbind(1, X)
			fast_mod <- RcppArmadillo::fastLmPure(mat, Y[,i])
			coeffs <- fast_mod$coefficients
			res[,i] <- Y[,i] - mat %*% coeffs
		}
	return(res)
	}
	
	A<-pro.residuals0(Y,X)
	B<-pro.residuals1(Y,X)
	D<-pro.residuals2(Y,X)


microbenchmark::microbenchmark(pro.residuals0(Y,X),pro.residuals1(Y,X),pro.residuals2(Y,X), times = 500)

@vanderleidebastiani
Copy link

	pro.residuals1.1<-function(Y,X){
		X<-sweep(X,2,colMeans(X,na.rm=TRUE),check.margin = FALSE)
		Y<-sweep(Y,2,colMeans(Y,na.rm=TRUE),check.margin = FALSE)
		Yfit<-X%*%solve(t(X)%*%X)%*%(t(X))%*%Y
		Yres<-Y-Yfit
	return(Yres)
	}

@aammd
Copy link
Author

aammd commented Dec 15, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment