7660
7660

Reputation: 107

R reorder column values alphabetic

i have a dataframe like this in R:

enter image description here

and i want to reorder the second column "Car" alphbethic like this:

Car

Audi/BMW/VW

Audi/BMW

Audi/BMW/VW

Audi/BMW/Porsche/VW

there could be 0 to 15 Cars with seperator "/"

my solution is a little bit complicated. (build a new DataFrame with this column, split them in multiple columns, reorder the rows alphabetic, paste them together, insert in original dataframe)

do you know a better and smarter solution?

thanks a lot

Upvotes: 1

Views: 65

Answers (2)

akrun
akrun

Reputation: 887831

We can use separate_rows to split the second column, then arrange by 'Name', and 'Car' and paste the elements grouped by 'Name'

library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
  separate_rows(Car) %>%
  arrange(Name, Car) %>%
  group_by(Name, zipcode) %>%
  summarise(Car = str_c(Car, collapse="/"))
# A tibble: 4 x 3
# Groups:   Name [4]
#  Name  zipcode Car                
#  <chr>   <dbl> <chr>              
#1 Frank    3456 Audi/BMW/VW        
#2 Lilly    1333 Audi/BMW/Porsche/VW
#3 Marie    1416 Audi/BMW           
#4 Peter    1213 Audi/BMW/VW      

data

df1 <- structure(list(Name = c("Peter", "Marie", "Frank", "Lilly"), 
    Car = c("BMW/VW/Audi", "Audi/BMW", "VW/BMW/Audi", "Audi/BMW/VW/Porsche"
    ), zipcode = c(1213, 1416, 3456, 1333)),
  class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389235

This is basically what you did but without creating new dataframe and new columns.

df$Car <- sapply(strsplit(as.character(df$Car), "/"), function(x)
                  paste(sort(x), collapse = "/"))

Upvotes: 2

Related Questions