[R] Basic question on concatenating factors

jim holtman jholtman at gmail.com
Sat Nov 22 16:20:57 CET 2008


Here is a function I have used.  I got it from the list, and
unfortunately don't remember who to credit:

 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
}


On Fri, Nov 21, 2008 at 12:29 PM, Alain Guillet
<alain.guillet at uclouvain.be> wrote:
> Hi,
>
> I have a solution to concatenate two factors in one but I don't believe
> it is the best one: factor(c(as.character(f1),as.character(f2)))
> [1] a a b b b a
> Levels: a b
>
>
> You can always add a level by assigning a new vector at the level vector:
> levels(f1) <- c("a","b","c")
> f1
> [1] a a b
> Levels: a b c
>
>
>
> udi cohen wrote:
>> Hi all,
>>
>> I hope it's not too trivial for the list - I'm trying to concatenate
>> two factor arrays, and obtain the following:
>>
>>
>>> f1<-factor(c("a","a","b"))
>>> f1
>>>
>> [1] a a b
>> Levels: a b
>>
>>> f2<-factor(c("b","b","a"))
>>> f2
>>>
>> [1] b b a
>> Levels: a b
>>
>>> c(f1,f2)
>>>
>> [1] 1 1 2 2 2 1
>>
>> Instead of getting:
>>
>> [1] a a b b b a
>> Levels: a b
>>
>> a related question is: how do I add a level which does not exists yet
>> in a factored vector, so I'll be able to add later these values,
>> without getting:
>>
>> In `[<-.factor`(`*tmp*`, 2, value = "c") :
>>   invalid factor level, NAs generated
>>
>> Thanks,
>>
>> EC
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>>
>
> --
> Alain Guillet
> Statistician and Computer Scientist
>
> SMCS - Institut de statistique - Université catholique de Louvain
> Bureau d.126
> Voie du Roman Pays, 20
> B-1348 Louvain-la-Neuve
> Belgium
>
> tel: +32 10 47 30 50
>
>
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list