Joining factor levels of two columns

前端 未结 3 1816
醉酒成梦
醉酒成梦 2020-12-06 06:18

I have 2 columns of data with the same type of data (Strings).

I want to join the levels of the columns. ie. we have:

col1   col2
Bob    John
Tom             


        
3条回答
  •  执笔经年
    2020-12-06 06:26

    You want the factors to include all the unique names from both columns.

    col1 <- factor(c("Bob", "Tom", "Frank", "Jim", "Tom"))
    col2 <- factor(c("John", "Bob", "Jane", "Bob", "Bob"))
    mynames <- unique(c(levels(col1), levels(col2)))
    fcol1 <- factor(col1, levels = mynames)
    fcol2 <- factor(col2, levels = mynames)
    

    EDIT: a little nicer if you replace the third line with this:

    mynames <- union(levels(col1), levels(col2))
    

提交回复
热议问题