Search code examples
rstringalphabetical-sort

Merging Columns and Alphabetizing Their Contents


I have a data frame called called issuesdata that I created from a larger frame, clean.data

issue1 <- as.vector(clean.data$issue1)
issue2 <- as.vector(clean.data$issue2)
issue3 <- as.vector(clean.data$issue3)
issuesdata <- data.frame(issue1, issue2, issue3)

issuesdata %>% dplyr::slice(10:15)
          issue1      issue2      issue3
1       economic        <NA>        <NA>
2       economic unification        <NA>
3       economic        <NA>        <NA>
4 transportation    aviation        <NA>
5        justice        <NA>        <NA>
6        slavery    economic humanrights

I have two goals:

  1. Merge these columns together such that there is a fourth column containing all the issues in one character string (column name: allissues)
  2. The text of the issues in allissues are alphabetized

For example, Row 2 of allissues would stay in the be in the form economic unification but be one character string. Row 4 would be Aviation Transportation, while Row 6 is economic humanrights slavery.

How do I go about doing this?


Solution

  • Rowwise drop NA values, sort them and paste them together.

    In base R :

    issuesdata$combine <- apply(issuesdata, 1, function(x) 
                                toString(sort(na.omit(x))))
    

    Or with dplyr :

    library(dplyr)
    
    issuesdata %>%
      rowwise() %>%
      mutate(combine = toString(sort(na.omit(c_across()))))
    
    #  issue1         issue2      issue3      combine_data                  
    #  <chr>          <chr>       <chr>       <chr>                         
    #1 economic       NA          NA          economic                      
    #2 economic       unification NA          economic, unification         
    #3 economic       NA          NA          economic                      
    #4 transportation aviation    NA          aviation, transportation      
    #5 justice        NA          NA          justice                       
    #6 slavery        economic    humanrights economic, humanrights, slavery