Search code examples
rdataframevertex

Combining categories of a dataframe in R


I am new to R and I have the following dataframe below with living_arrangements vertex on the y axis and loneliness_level vertex on the x axis. enter image description here

What would be the best way if I wanted to to combine Alternate between parents and partner and College or student accomodation into its own unique category called other so I have my dataframe like the one below instead?

                                    loneliness_level
living_arrangements       1 2 3 4 5 6 7 8 9 10
Alone                     1 1 0 2 0 1 1 3 1 4
Other                     1 2 5 2 2 1 2 3 1 0

Solution

  • If we want to get the sum, use rowsum

    out <- rowsum(m1, group = c(1, 2, 2))
    row.names(out) <- c("Alone", "Other")
    names(dimnames(out)) <- names(dimnames(m1))
    

    -output

    > out
                       loneliness_level
    living_arrangements 1 2 3 4 5 6 7 8 9 10
                  Alone 1 1 0 2 0 1 1 3 1  4
                  Other 1 2 5 2 2 1 2 3 1  0
    

    data

    m1 <- structure(c(1, 0, 1, 1, 0, 2, 0, 1, 4, 2, 0, 2, 0, 0, 2, 1, 0, 
    1, 1, 0, 2, 3, 0, 3, 1, 0, 1, 4, 0, 0), .Dim = c(3L, 10L), .Dimnames = list(
        living_arrangements = c("Alone", "Alternate between parents and partner", 
        "College or student accomodation"), loneliness_level = c("1", 
        "2", "3", "4", "5", "6", "7", "8", "9", "10")))