Joining factor levels of two columns

前端 未结 3 1817
醉酒成梦
醉酒成梦 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:43

    x <- structure(list(col1 = structure(c(1L, 4L, 2L, 3L, 4L), .Label = c("Bob", "Frank", "Jim", "Tom"), class = "factor"), col2 = structure(c(3L, 1L, 2L, 1L, 1L), .Label = c("Bob", "Jane", "John"), class = "factor")), .Names = c("col1", "col2"), class = "data.frame", row.names = c(NA, -5L))
    

    Make a simple union of factor names:

    both <- union(levels(x$col1), levels(x$col2))
    

    And relevel the two factors:

    x$col1 <- factor(x$col1, levels=both)
    x$col2 <- factor(x$col2, levels=both)
    

    After editing: added example to make numeric values from factors

    You could simply transform the factor levels to numeric values, e.g.:

    as.numeric(x$col1)
    

    Or a more simpler, nicer solution based on @Gavin Simpson's hint below in one step:

    data.matrix(x)
    

提交回复
热议问题