Hi,
I wanted to ask if it is possible to have a vctrs vector with a matrix or array as its underlying data, but that sits as a single column in a data.frame.
Just for context (may be skipped): I am developing a package for Functional Data Analysis, in which the observational unit is a function X_i(t). Most commonly, these functions come discretized over a common grid of values t_1,...,t_J and are thus represented by a data matrix X[i,j]=X_i(t_j) (with observations as rows). This matrix is the foundation I would like to have for my fd_vec class. Arrays as underlying data are also interesting for functions with multidimensional domains. This type of data would need to hold extra attributes, e.g. grid t_1,...,t_J itself and the domain range, which is why I do not work with a bare matrix.
I knew that data.frame() splits columns when given a matrix. I thought that behaviour would not be present if it was wrapped in a vctrs_vctr class, but the issue persists:
new_fd_vec <- function(
data = array(double(), dim = c(0, extra_dims)),
extra_dims = numeric(1L)
# <additional attributes...>
) {
if (!is.double(data) || !is.array(data)) {
rlang::abort("`data` must be a double matrix or array.")
}
vctrs::new_vctr(
data,
dim = dim(data),
class = "fd_vec"
)
}
fd1 <- new_fd_vec(array(1, c(10, 6)))
fd0 <- new_fd_vec(array(0, c(10, 2, 3)))
# --- with data.frame()
df <- data.frame(a = seq_len(10), b = fd1)
names(df) # b is decomposed in 6 columns
str(df)
df$c <- fd0
names(df) # this way c is a single column
str(df)
# here str(df$c) aborts, I dont really understand the issue as vec_slice() seems to work fine otherwise.
# i think that this problem would vanish if i defined a length method for `fd_vec` (not the main point anyway)
# --- with data_frame()
df <- data_frame(a = seq_len(10), b = fd1)
names(df) # b stays fine as a single column
str(df) # this errors too
# --- with tibble()
tb <- tibble::tibble(a = seq_len(10), b = fd1, c = fd0)
names(tb) # works fine as well
str(tb)
The behaviour above confused me a bit, and now I don't know if I should be expecting more surprises like this one or not.
I would like to know if matrices as underlying data are truly supported for vctrs S3 vectors. If that is the case
- am I doing anything very stupid?
- are there any fixes to the problem above with
data.frame(or should I simply only support tibbles)? - is there any other weird behaviour I should be wary of?
If instead matrices are not intended to be used this way, ¿what would be the best approach?
Update: I found out that regular data.frame/tibble printing also displays split columns, even if the data is a single component. Is there any way around it, or should i switch to something else?