[R] Splicing factors without losing levels
Ken Knoblauch
ken.knoblauch at inserm.fr
Tue Jun 9 11:27:00 CEST 2009
Titus von der Malsburg <malsburg <at> gmail.com> writes:
> An operation that I often need is splicing two vectors:
> > splice(1:3, 4:6)
> [1] 1 4 2 5 3 6
> For numeric vectors I use this hack:
> splice <- function(x, y) {
> xy <- cbind(x, y)
> xy <- t(xy)
> dim(xy) <- length(x) * 2
> return(xy)
> }
> So far, so good (?). But I also need splicing for factors and I tried
> this:
>
> splice <- function(x, y) {
> xy <- cbind(x, y)
> xy <- t(xy)
> dim(xy) <- length(x) * 2
> if (is.factor(x) && is.factor(y)) {
> xy <- as.factor(xy)
> levels(xy) <- levels(x)
> }
> return(xy)
> }
> This, however, doesn't work because the level name to integer mapping
> gets mixed up when copying the levels from x to xy.
> Thanks!!
> Titus
How about something like;:
splice.factor <- function(x, y){
if (!(is.factor(x) & is.factor(y)))
stop("Both x and y must be factors")
if (length(x) != length(y))
stop("Both x and y must have same length")
lx <- levels(x)
ly <- levels(y)
lxy <- union(lx, ly)
xy <- cbind(levels(x)[x], levels(y)[y])
xy <- t(xy)
dim(xy) <- NULL
xy <- factor(xy, levels = lxy)
xy
}
> splice.factor(factor(1:3), factor(4:6))
[1] 1 4 2 5 3 6
Levels: 1 2 3 4 5 6
--
Ken Knoblauch
Inserm U846
Stem-cell and Brain Research Institute
Department of Integrative Neurosciences
18 avenue du Doyen Lépine
69500 Bron
France
tel: +33 (0)4 72 91 34 77
fax: +33 (0)4 72 91 34 61
portable: +33 (0)6 84 10 64 10
http://www.sbri.fr/members/kenneth-knoblauch.html
More information about the R-help
mailing list