@@ -61,6 +61,9 @@ facet_wrap <- function(facets, nrow = NULL, ncol = NULL, scales = "fixed",
61
61
y = any(scales %in% c(" free_y" , " free" ))
62
62
)
63
63
64
+ nrow <- sanitise_dim(nrow )
65
+ ncol <- sanitise_dim(ncol )
66
+
64
67
facet(
65
68
facets = as.quoted(facets ), free = free , shrink = shrink ,
66
69
as.table = as.table , drop = drop ,
@@ -246,3 +249,59 @@ facet_axes.wrap <- function(facet, panel, coord, theme) {
246
249
facet_vars.wrap <- function (facet ) {
247
250
paste(lapply(facet $ facets , paste , collapse = " , " ), collapse = " ~ " )
248
251
}
252
+
253
+ # ' Sanitise the number of rows or columns
254
+ # '
255
+ # ' Cleans up the input to be an integer greater than or equal to one, or
256
+ # ' \code{NULL}. Intended to be used on the \code{nrow} and \code{ncol}
257
+ # ' arguments of \code{facet_wrap}.
258
+ # ' @param n Hopefully an integer greater than or equal to one, or \code{NULL},
259
+ # ' though other inputs are handled.
260
+ # ' @return An integer greater than or equal to one, or \code{NULL}.
261
+ # ' @note If the length of the input is greater than one, only the first element
262
+ # ' is returned, with a warning.
263
+ # ' If the input is not an integer, it will be coerced to be one.
264
+ # ' If the value is less than one, \code{NULL} is returned, effectively ignoring
265
+ # ' the argument.
266
+ # ' Multiple warnings may be generated.
267
+ # ' @examples
268
+ # ' # Valid input just gets returns unchanged
269
+ # ' sanitise_dim(1)
270
+ # ' sanitise_dim(NULL)
271
+ # ' \dontrun{
272
+ # ' # Only the first element of vectors get returned
273
+ # ' sanitise_dim(10:1)
274
+ # ' # Non-integer values are coerced to integer
275
+ # ' sanitise_dim(pi)
276
+ # ' # Missing values, values less than one and non-numeric values are
277
+ # ' # treated as NULL
278
+ # ' sanitise_dim(NA_integer_)
279
+ # ' sanitise_dim(0)
280
+ # ' sanitise_dim("foo")
281
+ # ' }
282
+ # ' @noRd
283
+ sanitise_dim <- function (n ) {
284
+ xname <- paste0(" `" , deparse(substitute(n )), " `" )
285
+ if (length(n ) == 0 ) {
286
+ if (! is.null(n )) {
287
+ warning(xname , " has length zero and will be treated as NULL." ,
288
+ call. = FALSE )
289
+ }
290
+ return (NULL )
291
+ }
292
+ if (length(n ) > 1 ) {
293
+ warning(" Only the first value of " , xname , " will be used." , call. = FALSE )
294
+ n <- n [1 ]
295
+ }
296
+ if (! is.numeric(n ) || (! is.na(n ) && n != round(n ))) {
297
+ warning(" Coercing " , xname , " to be an integer." , call. = FALSE )
298
+ n <- as.integer(n )
299
+ }
300
+ if (is.na(n ) || n < 1 ) {
301
+ warning(xname , " is missing or less than 1 and will be treated as NULL." ,
302
+ call. = FALSE )
303
+ return (NULL )
304
+ }
305
+ n
306
+ }
307
+
0 commit comments