Permalink
Browse files

Tweaks to each

  • Loading branch information...
1 parent a2f34cf commit 9a66056401d24619e7230b0ee93bc98e873d0fec @hadley committed Apr 15, 2009
Showing with 26 additions and 16 deletions.
  1. +22 −13 R/helper-each.r
  2. +2 −2 R/ply-list.r
  3. +2 −1 R/simplify-vector.r
View
35 R/helper-each.r
@@ -33,19 +33,28 @@ each <- function(...) {
n <- length(fs)
proto <- NULL
- function(x, ...) {
-
- # 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, ...)
+ if (n == 1) {
+ # If there is only one function, things are simple. We just
+ # need to name the output, if appopriate.
+ function(x, ...) {
+ res <- fs[[1]](x, ...)
+ if (length(res) == 1) names(res) <- unames
+ res
}
- proto
-
+ } else {
+ function(x, ...) {
+ # For n > 1 things are a little tricky
+ # 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
4 R/ply-list.r
@@ -30,8 +30,8 @@ llply <- function(.data, .fun = NULL, ..., .progress = "none", .inform = FALSE)
n <- length(pieces)
if (n == 0) return(list())
- if (is.character(.fun)) .fun <- match.fun(.fun)
- # .fun <- do.call("each", as.list(.fun))
+ if (is.character(.fun)) .fun <- each(.fun)
+ # .fun <- each(.fun)
if (!is.function(.fun)) stop(".fun is not a function.")
progress <- create_progress_bar(.progress)
View
3 R/simplify-vector.r
@@ -4,8 +4,9 @@
# @arguments list of input data
# @keyword internal
list_to_vector <- function(res) {
- if (length(res) == 0) return(vector())
n <- length(res)
+ if (n == 0) return(vector())
+ if (n == 1) return(res[[1]])
atomic <- sapply(res, is.atomic)
if (all(atomic)) {

0 comments on commit 9a66056

Please sign in to comment.