summaryrefslogtreecommitdiff
path: root/R/util.R
blob: bf928085ec4bba35555d0395aea6e91a07be4c2f (plain)
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
# Generic form
#' Multiple assignment operator
#' 
#' Assign multiple variables from a list or function return object
#' 
#' @param l,r the variables to be assigned, and the list or 
#' function return object
#' 
#' @export
'%=%' = function(l, r, ...) UseMethod('%=%')

# Binary Operator
#' @export
'%=%.lbunch' = function(l, r, ...) {
  Envir = as.environment(-1)
  
#   if (length(r) > length(l))
#     warning("RHS has more args than LHS. Only first", length(l), "used.")
  
  if (length(l) > length(r))  {
    warning("LHS has more args than RHS. RHS will be repeated.")
    r <- extendToMatch(r, l)
  }
  
  for (II in 1:length(l)) {
    do.call('<-', list(l[[II]], r[[II]]), envir=Envir)
  }
}

# Used if LHS is larger than RHS
extendToMatch <- function(source, destin) {
  s <- length(source)
  d <- length(destin)
  
  # Assume that destin is a length when it is a single number and source is not
  if(d==1 && s>1 && !is.null(as.numeric(destin)))
    d <- destin
  
  dif <- d - s
  if (dif > 0) {
    source <- rep(source, ceiling(d/s))[1:d]
  }
  return (source)
}

# Grouping the left hand side
#' @export
g = function(...) {
  List = as.list(substitute(list(...)))[-1L]
  class(List) = 'lbunch'
  return(List)
}