summaryrefslogtreecommitdiff
path: root/R/util.R
blob: f58c3fbec2f45448bd9169aa24877d5b67942f3b (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
53
54
55
# Generic form
#' Multiple assignment operator
#' 
#' Assign multiple variables from a list or function return object
#' 
#' @param l the variables to be assigned
#' @param r the list or function-return object
#' @param \ldots other arguments
#' 
#' @aliases g
#' 
#' @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)
}