-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathshape.R
100 lines (84 loc) · 2.34 KB
/
shape.R
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
# The dimensionality of an matrix/array is partition into two parts:
# * the first dimension = the number of observations
# * all other dimensions = the shape parameter of the type
# These helpers work with the shape parameter
new_shape <- function(type, shape = integer()) {
structure(type, dim = c(0L, shape))
}
vec_shaped_ptype <- function(ptype, x, y, ..., x_arg = "", y_arg = "") {
check_dots_empty0(...)
.Call(ffi_vec_shaped_ptype, ptype, x, y, environment())
}
vec_shape2 <- function(x, y, ..., x_arg = "", y_arg = "") {
check_dots_empty0(...)
.Call(ffi_vec_shape2, x, y, environment())
}
# Should take same signature as `vec_cast()`
shape_broadcast <- function(x,
to,
...,
x_arg,
to_arg,
call = caller_env()) {
if (is.null(x) || is.null(to)) {
return(x)
}
dim_x <- vec_dim(x)
dim_to <- vec_dim(to)
# Don't set dimensions for vectors
if (length(dim_x) == 1L && length(dim_to) == 1L) {
return(x)
}
if (length(dim_x) > length(dim_to)) {
details <- sprintf(
"Can't decrease dimensionality from %s to %s.",
length(dim_x),
length(dim_to)
)
stop_incompatible_cast(
x,
to,
details = details,
x_arg = x_arg,
to_arg = to_arg,
call = call
)
}
dim_x <- n_dim2(dim_x, dim_to)$x
dim_to[[1]] <- dim_x[[1]] # don't change number of observations
ok <- dim_x == dim_to | dim_x == 1
if (any(!ok)) {
stop_incompatible_cast(
x,
to,
details = "Non-recyclable dimensions.",
x_arg = x_arg,
to_arg = to_arg,
call = call
)
}
# Increase dimensionality if required
if (vec_dim_n(x) != length(dim_x)) {
dim(x) <- dim_x
}
recycle <- dim_x != dim_to
# Avoid expensive subset
if (all(!recycle)) {
return(x)
}
indices <- rep(list(missing_arg()), length(dim_to))
indices[recycle] <- map(dim_to[recycle], rep_len, x = 1L)
eval_bare(expr(x[!!!indices, drop = FALSE]))
}
# Helpers -----------------------------------------------------------------
n_dim2 <- function(x, y) {
nx <- length(x)
ny <- length(y)
if (nx == ny) {
list(x = x, y = y)
} else if (nx < ny) {
list(x = c(x, rep(1L, ny - nx)), y = y)
} else {
list(x = x, y = c(y, rep(1L, nx - ny)))
}
}