Skip to content

Commit 871ae81

Browse files
committed
check length of list elements and better check for numeric coercion
1 parent 6ec50ff commit 871ae81

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

R/utils.R

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -670,24 +670,28 @@ colorscale_json <- function(x) {
670670
x <- as.data.frame(x)
671671
x[, 1] <- as.numeric(x[, 1])
672672
}
673+
# ensure a list like this: list(list(0, 0.5, 1), list("red", "white", "blue"))
674+
# converts to the correct dimensions: [[0, 'red'], [0.5, 'white'], [1, 'blue']]
673675
if (is.list(x) && length(x) == 2) {
674-
# ensure a list like this: list(list(0, 0.5, 1), list("red", "white", "blue"))
675-
# converts to the correct dimensions
676-
if (!is.data.frame(x) && can_be_numeric(x[[1]])) {
676+
n1 <- length(x[[1]])
677+
n2 <- length(x[[2]])
678+
if (n1 != n2 || n1+n2 == 0) {
679+
warning("A colorscale list must of elements of the same (non-zero) length")
680+
} else if (!is.data.frame(x) && can_be_numeric(x[[1]])) {
677681
x <- data.frame(
678682
val = as.numeric(x[[1]]),
679683
col = as.character(x[[2]]),
680684
stringsAsFactors = FALSE
681685
)
686+
x <- setNames(x, NULL)
682687
}
683-
x <- setNames(x, NULL)
684688
}
685689
x
686690
}
687691

688692
can_be_numeric <- function(x) {
689-
x <- suppressWarnings(as.numeric(x))
690-
sum(is.na(x)) == 0
693+
xnum <- suppressWarnings(as.numeric(x))
694+
sum(is.na(x)) == sum(is.na(xnum))
691695
}
692696

693697
# if an object (e.g. trace.marker) contains a non-default attribute, it has been user-specified

0 commit comments

Comments
 (0)