Permalink
Browse files

Tweaks to each to make it more robust

  • Loading branch information...
hadley committed Apr 11, 2009
1 parent 59192b9 commit 4b6ba09f820c08a63ac8265175d1a0a180471112
Showing with 33 additions and 4 deletions.
  1. +14 −4 R/helper-each.r
  2. +19 −0 R/simplify-vector.r
View
@@ -21,11 +21,21 @@ each <- function(...) {
unames[unames == ""] <- fnames[unames == ""]
n <- length(fs)
+ proto <- NULL
function(x, ...) {
- results <- vector("numeric", length=n)
- for(i in 1:n) results[[i]] <- fs[[i]](x, ...)
- names(results) <- unames
- results
+
+ # Construct prtotype for output on first call
+ if (is.null(proto)) {
+ result <<- vector("list", length = n)
+ names(result) <- unames
+
+ for(i in 1:n) result[[i]] <- fs[[i]](x, ...)
+ proto <<- list_to_vector(result)
+ } else {
+ for(i in 1:n) proto[[i]] <- fs[[i]](x, ...)
+ }
+ proto
+
}
}
View
@@ -0,0 +1,19 @@
+# List to vector
+# Reduce/simplify a list of homogenous objects to a vector
+#
+# @arguments list of input data
+# @keywords internal
+list_to_vector <- function(res) {
+ if (length(res) == 0) return(vector())
+ n <- length(res)
+
+ atomic <- sapply(res, is.atomic)
+ if (all(atomic)) {
+ classes <- unique(lapply(res, class))
+ if (length(classes) == 1) {
+ res <- unlist(res)
+ }
+ }
+
+ res
+}

0 comments on commit 4b6ba09

Please sign in to comment.