Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

stupid.script.R

By: a guest on Apr 4th, 2013  |  syntax: R  |  size: 0.98 KB  |  views: 166  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. # create big data frame:
  2. n <- 1000
  3. x <- data.frame(group = sample(letters[1:4], n, replace=TRUE), condition = sample(LETTERS[1:10], n, replace = TRUE), data = rnorm(n))
  4.  
  5. # reasonable operations:
  6. marginal.means.1 <- aggregate(data ~ group + condition, data = x, FUN=mean)
  7.  
  8. # unreasonable operations:
  9. marginal.means.2 <- marginal.means.1[NULL,]
  10.  
  11. row.counter <- 1
  12. for (condition in levels(x$condition)) {
  13.   for (group in levels(x$group)) {  
  14.     tmp.value <- 0
  15.     tmp.length <- 0
  16.     for (c in 1:nrow(x)) {
  17.       if ((x[c,"group"] == group) & (x[c,"condition"] == condition)) {
  18.         tmp.value <- tmp.value + x[c,"data"]
  19.         tmp.length <- tmp.length + 1
  20.       }
  21.     }
  22.     marginal.means.2[row.counter,"group"] <- group
  23.     marginal.means.2[row.counter,"condition"] <- condition
  24.     marginal.means.2[row.counter,"data"] <- tmp.value / tmp.length
  25.     row.counter <- row.counter + 1
  26.   }
  27. }
  28.  
  29. # does it produce the same results?
  30. all.equal(marginal.means.1, marginal.means.2)
clone this paste RAW Paste Data