Bug 14288 - bug in cut.POSIXt(..., breaks = <numeric>) and cut.Date
bug in cut.POSIXt(..., breaks = <numeric>) and cut.Date
Status: RESOLVED FIXED
Product: R
Classification: Unclassified
Component: Misc
R 2.12.0
ix86 (32-bit) Windows 32-bit
: P5 minor
Assigned To: R-core
Depends on:
Blocks:
  Show dependency treegraph
 
Reported: 2010-05-07 00:46 UTC by Felix Andrews
Modified: 2014-02-16 11:43 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Felix Andrews 2010-05-07 00:46:35 UTC
cut() fails when a number of breaks is specified with a POSIXt or Date object.


x <- seq(as.POSIXct("2000-01-01"), by = "days", length = 20)

cut(x, breaks = 3)
# Error in `levels<-.factor`(`*tmp*`, value = character(0)) :
#   number of levels differs

cut(as.Date(x), breaks = 3)
# Error in `levels<-.factor`(`*tmp*`, value = character(0)) :
#   number of levels differs


Suggested fix:


Index: base/R/datetime.R
===================================================================
--- base/R/datetime.R   (revision 51857)
+++ base/R/datetime.R   (working copy)
@@ -775,7 +775,11 @@
        }
    } else stop("invalid specification of 'breaks'")
    res <- cut(unclass(x), unclass(breaks), labels = labels, right =
right, ...)
-    if(is.null(labels)) levels(res) <- as.character(breaks[-length(breaks)])
+    if(is.null(labels)) {
+        if (is.numeric(breaks))
+            levels(res) <- as.character(x[!duplicated(res)])
+        else levels(res) <- as.character(breaks[-length(breaks)])
+    }
    res
 }

Index: base/R/dates.R
===================================================================
--- base/R/dates.R      (revision 51857)
+++ base/R/dates.R      (working copy)
@@ -362,7 +362,11 @@
    } else stop("invalid specification of 'breaks'")
    res <- cut(unclass(x), unclass(breaks), labels = labels,
               right = right, ...)
-    if(is.null(labels)) levels(res) <- as.character(breaks[-length(breaks)])
+    if(is.null(labels)) {
+        if (is.numeric(breaks))
+            levels(res) <- as.character(x[!duplicated(res)])
+        else levels(res) <- as.character(breaks[-length(breaks)])
+    }
    res
 }
Comment 1 Martin Maechler 2010-05-07 07:55:50 UTC
Thank you, Felix.

I'm fixing this for R-devel (+ R-patched = 2.11.1 to be)
Comment 2 Martin Maechler 2010-05-07 09:50:14 UTC
fixed in svn rev 51928 & 51929
Comment 3 Jackie Rosen 2014-02-16 11:43:45 UTC
(spam comment removed)