Bug 16144 - enhancement to base::structure to prevent malformed factors
Summary: enhancement to base::structure to prevent malformed factors
Status: NEW
Alias: None
Product: R
Classification: Unclassified
Component: Wishlist (show other bugs)
Version: R 3.1.2
Hardware: Other All
: P5 enhancement
Assignee: R-core
URL:
Depends on:
Blocks:
 
Reported: 2015-01-09 00:40 UTC by Benjamin Tyner
Modified: 2015-01-09 00:40 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Benjamin Tyner 2015-01-09 00:40:00 UTC
Somewhat related to Duncan's suggestion in bug 15300, to reduce the likelihood of creating a malformed factor, here is a patch

Index: src/library/base/R/structure.R
===================================================================
--- src/library/base/R/structure.R	(revision 67375)
+++ src/library/base/R/structure.R	(working copy)
@@ -28,9 +28,14 @@
 	ok <- (!is.na(m) & m)
 	names(attrib)[ok] <- replace[m[ok]]
         ## prior to 2.5.0 factors would deparse to double codes
-	if("factor" %in% attrib[["class", exact = TRUE]]
-           && typeof(.Data) == "double")
-	   storage.mode(.Data) <- "integer"
+        if("factor" %in% attrib[["class", exact = TRUE]]) {
+           if(typeof(.Data) == "double") {
+              storage.mode(.Data) <- "integer"
+           }
+           if(any(.Data < 1L, na.rm = TRUE)) {
+              stop("integer codes must be positive")
+           }
+        }
 	attributes(.Data) <- c(attributes(.Data), attrib)
     }
     return(.Data)