File: insert.R

package info (click to toggle)
r-cran-r.utils 2.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,936 kB
  • sloc: sh: 18; makefile: 6
file content (187 lines) | stat: -rwxr-xr-x 5,756 bytes parent folder | download
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#########################################################################/**
# @RdocDefault insert
#
# @title "Insert values to a vector at certain positions"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{x}{The @vector of data values.}
#   \item{ats}{The indices of \code{x} where the values should be inserted.}
#   \item{values}{A @list or a @vector of the values to be inserted.
#      Should be of same length as \code{ats}, unless if a single value
#      when it is automatically extended without a warning.}
#   \item{useNames}{If @FALSE, the names attribute is dropped/ignored,
#      otherwise not.  Only applied if argument \code{x} is named.}
#   \item{...}{Not used.}
# }
#
# @examples "../incl/insert.Rex"
#
# \seealso{
#   @see "base::append" takes argument \code{after} (a scalar).  For example,
#   \code{append(x, y, after=after) == insert(x, values=y, ats=after+1)}.
#   Contrary to \code{append()}, \code{insert()} accepts a vector of insert indices.
# }
#
# @author
#
# @keyword "manip"
#*/#########################################################################t
setMethodS3("insert", "default", function(x, ats, values=NA, useNames=TRUE, ...) {
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Local functions
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # For debug only!
##   printFromTo <- function(from, to, x) {
##     fromto <- matrix(c(from, to), ncol=2);
##     colnames(fromto) <- c("from", "to");
##     idx <- apply(fromto, MARGIN=1, FUN=function(i) seqToHumanReadable(i[1]:i[2]));
##     xidx <- apply(fromto, MARGIN=1, FUN=function(i) paste(x[i[1]:i[2]], collapse=","));
##     print(data.frame(from=from, to=to, idx=idx, x.=xidx))
##   }

  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Validate arguments
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  if (!is.vector(x))
    throw("Argument 'x' is not a vector: ", class(x));

  len <- length(x);
  if (any(ats < 1 | ats > len+1))
    throw("Argument 'ats' contains indices out of range: ", paste(ats, collapse=", "));

  if (any(duplicated(ats)))
    throw("Argument 'ats' contains duplicated indices: ", paste(ats, collapse=", "));

  if (!is.vector(values))
    throw("Argument 'values' is not a vector: ", class(values));

  # Argument 'useNames':
  useNames <- as.logical(useNames);

  # Deal with the names attribute too?
  if (useNames) {
    names <- names(x);
    useNames <- (!is.null(names));
  }

  if (!is.list(values)) {
    if (length(ats) == 1) {
      values <- list(values);
    } else {
      values <- as.list(values);
    }
  }

  if (length(ats) != length(values)) {
    if (length(values) == 1) {
      values <- rep(values, length.out=length(ats));
    } else {
      throw("Argument 'ats' and argument 'values' has different lengths: ",
                                       length(ats), " != ", length(values));
    }
  }

  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Setup
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Sort the 'ats' indicies
  o <- order(ats);
  ats <- ats[o];
  values <- values[o];

  nvalues <- unlist(lapply(values, FUN=length));

  # Allocate the result vector
  n2 <- length(x) + sum(nvalues);
  x2 <- vector(mode=mode(x), length=n2);
  storage.mode(x2) <- storage.mode(x);
  if (useNames)
    names2 <- character(n2);

  # 'ats' positions in the result vector
  n <- length(ats);
  ats2 <- ats + c(0, cumsum(nvalues[-n]));

  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Assign inserted values
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  for (kk in 1:length(ats2)) {
    idx2 <- ats2[kk] + 0:(nvalues[kk]-1);
    valuesKK <- values[[kk]];
    x2[idx2] <- valuesKK;
    if (useNames) {
      valueNames <- names(valuesKK);
      if (is.null(valueNames))
        valueNames <- character(length(valuesKK));
      names2[idx2] <- valueNames;
    }
  }

  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Assign original values
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  froms <- c(1, ats);
  tos <- c(ats-1, length(x));
  froms2 <- c(1, ats2+nvalues);

  if (ats[1] == 1) {
    froms <- froms[-1];
    tos <- tos[-1];
    froms2 <- froms2[-1];
  }

  if (ats[n] > length(x)) {
    froms <- froms[-length(froms)];
    tos <- tos[-length(tos)];
    froms2 <- froms2[-length(froms2)];
  }

  ns <- tos-froms+1;
  tos2 <- froms2 + ns - 1;

  for (kk in seq_along(froms2)) {
    from <- froms[kk];
    to <- tos[kk];
    from2 <- froms2[kk];
    to2 <- tos2[kk];
    idx <- from:to;
    idx2 <- from2:to2;
    x2[idx2] <- x[idx];
    if (useNames)
      names2[idx2] <- names[idx];
  }

  if (useNames)
    names(x2) <- names2;

  x2;
})


############################################################################
# HISTORY:
# 2012-09-21
# o Now insert() silently expands 'values' to be of the same length
#   as 'ats', iff length(values) == 1.
# 2008-12-27
# o Added argument 'useNames' to insert(), which is now aware of names
#   of the input object.
# 2008-03-31
# o BUG FIX: If 'x' in insert(x, ...) was zero length, an "Error in from:to
#   : NA/NaN argument" was thrown.
# 2008-02-21
# o BUG FIX: When 'values' was a non-list its values were placed in a
#   single-element list.  Should have been as.list().
# 2005-06-12
# o Updated a lot! Wrote a rather large example.
# 2005-02-20
# o Now using setMethodS3() and added '...' to please R CMD check.
# 2001-11-24
# o Created.
############################################################################