Skip to content

Commit 2ef5c24

Browse files
committed
Support for 3-vector in xyzmatrix.default
* I have done this in many places where I use xyzmatrix, so probably should have changed long ago ... * also added better error message wxen we don't managed to make and Nx3 matrix * includes test
1 parent 394baa0 commit 2ef5c24

3 files changed

Lines changed: 17 additions & 2 deletions

File tree

R/xyzmatrix.R

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,10 @@ xyzmatrix<-function(x, ...) UseMethod("xyzmatrix")
2929
#' \code{matrix} or \code{data.frame} that \bold{either} has exactly 3 columns
3030
#' \bold{or} has 3 columns named X,Y,Z or x,y,z. As of Nov 2020, if these
3131
#' columns are character vectors, they will be correctly converted to numeric
32-
#' (with a warning for any NA values).
32+
#' (with a warning for any NA values). As of Jan 2021 if \code{x} is a numeric
33+
#' vector containing exactly 3 numbers it will be parsed as a 1x3 matrix.
34+
#' Support has also been added for setting a list containing 3-vectors in each
35+
#' element.
3336
#'
3437
#' @section Getting and setting from character vectors:
3538
#'
@@ -73,8 +76,13 @@ xyzmatrix.default<-function(x, y=NULL, z=NULL, ...) {
7376
if(!any(is.na(matched_cols))) x=x[, matched_cols, drop=FALSE]
7477
else stop("Ambiguous column names. Unable to retrieve XYZ data")
7578
} else if(ncol(x)<3) stop("Must have 3 columns of XYZ data")
79+
} else if(is.numeric(x) && length(x)==3) {
80+
x=matrix(x, ncol=3)
7681
}
82+
7783
mx=as.matrix(x)
84+
if(ncol(mx)!=3)
85+
stop("Cannot make an Nx3 coordinate matrix")
7886
if(mode(mx)=='character'){
7987
tryCatch(mode(mx) <- 'numeric',
8088
warning=function(w, ...) warning("xyzmatrix: ", w, call. = F))

man/xyzmatrix.Rd

Lines changed: 4 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/testthat/test-xyzmatrix.R

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
test_that("can extract xyz coords from a matrix and other objects",{
2+
# special case of 3-vector
3+
expect_equal(xyzmatrix(1:3), xyzmatrix(1,2,3))
4+
expect_error(xyzmatrix(1:4))
5+
26
mx=matrix(1:24,ncol=3)
37
expect_equivalent(xyzmatrix(mx),mx)
48
colnames(mx)=c("X","Y","Z")

0 commit comments

Comments
 (0)