Hello!
Does R core find the following pacth usefull - I created methods for
levels for list and data.frame, which can be usefull to get a list of
levels for entries in a list or columns in a data.frame. Patch is
attached and shown bellow example
# Example
tmp <- list()
tmp$a <- factor(letters[1:10])
tmp$b <- factor(letters[5:14])
tmp$c <- 1:10
tmp1 <- as.data.frame(tmp)
tmp2 <- list()
tmp2$"1" <- tmp
tmp2$"2" <- tmp1
str(tmp2)
List of 2
$ 1:List of 3
..$ a: Factor w/ 10 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10
..$ b: Factor w/ 10 levels "e","f","g","h",..: 1 2 3 4 5 6 7 8 9 10
..$ c: int [1:10] 1 2 3 4 5 6 7 8 9 10
$ 2:`data.frame': 10 obs. of 3 variables:
..$ a: Factor w/ 10 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10
..$ b: Factor w/ 10 levels "e","f","g","h",..: 1 2 3 4 5 6 7 8 9 10
..$ c: int [1:10] 1 2 3 4 5 6 7 8 9 10
$"1"
$"1"$a
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
$"1"$b
[1] "e" "f" "g" "h" "i" "j" "k" "l" "m" "n"
$"2"
$"2"$a
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
$"2"$b
[1] "e" "f" "g" "h" "i" "j" "k" "l" "m" "n"
levels(tmp2, drop = FALSE)
$"1"
$"1"$a
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
$"1"$b
[1] "e" "f" "g" "h" "i" "j" "k" "l" "m" "n"
$"1"$c
NULL
$"2"
$"2"$a
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
$"2"$b
[1] "e" "f" "g" "h" "i" "j" "k" "l" "m" "n"
$"2"$c
NULL
----------------------------------------------------------------------
$ svn diff factor.R
Index: factor.R
===================================================================
--- factor.R (revision 37559)
+++ factor.R (working copy)
@@ -25,7 +25,25 @@
## Help old S users:
category <- function(...) .Defunct()
-levels <- function(x) attr(x, "levels")
+levels <- function(x, ...) UseMethod("levels")
+
+levels.default <- function(x, ...) attr(x, "levels")
+
+levels.list <- function(x, drop = TRUE)
+{
+ tmp <- lapply(x, levels, drop = drop)
+ if (drop) {
+ tmp1 <- unlist(lapply(tmp, is.null))
+ tmp <- tmp[!tmp1]
+ }
+ return(tmp)
+}
+
+levels.data.frame <- function(x, ...)
+{
+ return(levels.list(x, ...))
+}
+
nlevels <- function(x) length(levels(x))
"levels<-" <- function(x, value) UseMethod("levels<-")