# Re: [Rd] c.factor

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Tue 14 Nov 2006 - 17:51:25 GMT

On Tue, 2006-11-14 at 16:36 +0000, Matthew Dowle wrote:
> Hi,
>
> Given factors x and y, c(x,y) does not seem to return a useful result :
> > x
> [1] a b c d e
> Levels: a b c d e
> > y
> [1] d e f g h
> Levels: d e f g h
> > c(x,y)
> [1] 1 2 3 4 5 1 2 3 4 5
> >
>
> Is there a case for a new method c.factor as follows? Does something
> similar exist already? Is there a better way to write the function?
>
> > c.factor = function(x,y)
> {
> newlevels = union(levels(x),levels(y))
> m = match(levels(y), newlevels)
> ans = c(unclass(x),m[unclass(y)])
> levels(ans) = newlevels
> class(ans) = "factor"
> ans
> }
> > c(x,y)
> [1] a b c d e d e f g h
> Levels: a b c d e f g h
> > as.integer(c(x,y))
> [1] 1 2 3 4 5 4 5 6 7 8
> >
>
> Regards,
> Matthew

I'll defer to others as to whether or not there is a basis for c.factor, however:

c.factor <- function(...)
{
args <- list(...)

# this could be optional
if (!all(sapply(args, is.factor)))
stop("All arguments must be factors")

factor(unlist(lapply(args, function(x) as.character(x)))) }

```x <- factor(letters[1:5])
y <- factor(letters[4:8])
z <- factor(letters[9:14])

```

> x

[1] a b c d e
Levels: a b c d e

> y

[1] d e f g h
Levels: d e f g h

> z

[1] i j k l m n
Levels: i j k l m n

> c(x, y)
[1] a b c d e d e f g h
Levels: a b c d e f g h

> c(x, y, z)
[1] a b c d e d e f g h i j k l m n
Levels: a b c d e f g h i j k l m n

> c(x, 1:5)
Error in c.factor(x, 1:5) : All arguments must be factors

HTH, Marc Schwartz

R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Wed Nov 15 05:25:26 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 14 Nov 2006 - 18:30:42 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.