The automatic conversion of 2D data.frame or matrix to 1D vectors, also good, makes some problems while writing generic functions. For example trying to filter some columns of the input foo with a command like foo[,1:3] works fine for a data.frame or matrix:
foo=matrix(1:9,nrow=3)
bar = function(x) print(x[,1])
bar(foo) # [1] 1 2 3
But consider we first want to filter some rows of foo, and it happens that only a single row remains:
bar(foo[1,]) # Error in x[, 1] : incorrect number of dimensions
This problem may be solved by a simple trick:
bar = function(x) {
if (is.null(dim(x))) x = t(data.frame(x))
print(x[,1])
}
But the problem would be much more complicated if we have other filters on x in the body of bar() that may convert it again to a vector. Then for every filtering we should check and do the same to ensure what we have is still a table.
The other problems are: missing row names and/or column names if the filtered part of a matrix is only a single row/column. It needs further manipulation to re-organize the filtered part as a matrix, retrieve the original row/column names and assign them to the resulting matrix.
The question is that: How to simply convert a function that works for tables a generic one, that if the input happens to be vector it still works?
I have similar problems when working with data that could be a vector or a data.frame.
Usually, I just create a subset function within the function.
This method also maintains the class of the original object.