Guest User

Untitled

a guest
Apr 7th, 2014
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.22 KB | None | 0 0
  1. start.time = Sys.time()
  2. set.seed(5)
  3. no = 10
  4. np = 20
  5. nr = 4
  6. d = 4
  7. X = matrix(rnorm(no*np*nr*d),ncol = d)
  8. X = data.frame(operator = rep(1:no,np*nr), part = rep(1:np, no,, nr), replication = rep(1:nr,,, no*np), X)
  9. Mat_exp = expand.grid(1:no, 1:np)
  10.  
  11. Reduce('+', lapply(1:nrow(Mat_exp), function(i){
  12.     M = t(as.matrix(X[,4:ncol(X)]))
  13.     X_demean = M - rowMeans(M[,X$operator == Mat_exp[i,1]]) - rowMeans(M[,X$part == Mat_exp[i,2]]) + mean(M)
  14.     X_demean %*% t(X_demean)
  15. })) / (nrow(X) - no - np + nr)
  16. Sys.time() - start.time
  17.  
  18. library(plyr)
  19. library(data.table)
  20. rm(list=ls(all=TRUE))
  21. start.time = Sys.time()
  22. set.seed(5)
  23. no = 10
  24. np = 20
  25. nr = 4
  26. d = 4
  27. X = matrix(rnorm(no*np*nr*d),ncol = d)
  28. X = data.table(operator = rep(1:no,np*nr), part = rep(1:np, no,, nr), replication = rep(1:nr,,, no*np), X)
  29. setkey(X, operator,part)
  30. Mat_exp = expand.grid(1:no, 1:np)
  31. Reduce('+', alply(matrix(1:nrow(Mat_exp),,1),1, function(i){
  32.     X_demean = apply(X[, 4:ncol(X), with = FALSE], 1, function(v) v-colMeans(X[J(1:no,Mat_exp[i,2]), 4:ncol(X), with = FALSE])-colMeans(X[J(Mat_exp[i,1],1:np), 4:ncol(X), with = FALSE])) + mean(colMeans(X[, 4:ncol(X), with = FALSE]))
  33.     X_demean %*% t(X_demean)
  34. })) / (nrow(X) - no - np + nr)
  35. Sys.time() - start.time
Advertisement
Add Comment
Please, Sign In to add comment