File: iteratorTest.R

package info (click to toggle)
r-cran-foreach 1.4.2-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 772 kB
  • ctags: 3
  • sloc: sh: 58; makefile: 1
file content (82 lines) | stat: -rw-r--r-- 2,034 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# test matrix iterator with foreach
test01 <- function() {
  m <- matrix(rnorm(25 * 16), 25)

  x <- foreach(col=iter(m, by='col'), .combine='cbind') %do% col
  checkEquals(m, x)

  x <- foreach(col=iter(m, by='col'), .combine='cbind') %dopar% col
  checkEquals(m, x)

  x <- foreach(row=iter(m, by='row'), .combine='rbind') %do% row
  checkEquals(m, x)

  x <- foreach(row=iter(m, by='row'), .combine='rbind') %dopar% row
  checkEquals(m, x)
}

# test data.frame iterator with foreach
test02 <- function() {
  d <- data.frame(a=1:10,b=11:20,c=21:30)
  ed <- data.matrix(d)

  x <- foreach(col=iter(d, by='col'), .combine='cbind') %do% col
  colnames(x) <- colnames(ed)
  checkEquals(ed, x)

  x <- foreach(col=iter(d, by='col'), .combine='cbind') %dopar% col
  colnames(x) <- colnames(ed)
  checkEquals(ed, x)

  x <- foreach(row=iter(d, by='row'), .combine='rbind') %do% row
  checkEquals(d, x)

  x <- foreach(row=iter(d, by='row'), .combine='rbind') %dopar% row
  checkEquals(d, x)
}

# test function iterator with foreach and %do%
test03 <- function() {
  
  func <- function() {
    y = NULL
    repeat {
      x = rnorm(1)
      if (x < -3.0) stop('StopIteration')
      if (10 == length(y))
        break
      else
        if (0 < x) y = c(y, x)
    }
    y
  }

  ## XXX mean is not a reasonable combine function
  ## XXX removed this for the moment - sbw
  ## r <- foreach(v=iter(func), .combine='mean') %do% mean(v)
  ## 'r' is NULL if iteration stops early.
  ## checkTrue(is.null(r) || 0 < r)
}

# test function iterator with foreach and %dopar%
test04 <- function() {

  func <- function() {
    y = NULL
    repeat {
      x = rnorm(1)
      if (x < -3.0) stop('StopIteration')
      if (10 == length(y))
        break
      else
        if (0 < x) y = c(y, x)
    }
    y
  }

  ## XXX mean is not a reasonable combine function
  ## XXX removed this for the moment - sbw
  ## r <- foreach(v=iter(func), .combine='mean') %dopar% mean(v)
  ## 'r' is NULL if iteration stops early.
  ## checkTrue(is.null(r) || 0 < r)
}