Question: Have a look at the dataframe (df) below.

| Date | Modules |
| --- | --- |
| 26-11-2021 | NA, Advanced chemistry, Biochemistry |
| 25-11-2021 | Food physics, Food chemistry |

I would like to alphabetically order the content of the modules column. Desired output:

| Date | Modules |
| --- | --- |
| 26-11-2021 | Advanced chemistry, Biochemistry, NA |
| 25-11-2021 | Food chemistry, Food physics |

To achieve said result I have tried the following:

`df[lapply(strsplit(as.character(df$Modules), ','), sort)),]`

Without succes sadly. What fundamental mistake do I make?

Answer: 
collapse the sorted string back into one string using `toString`.

```
df$Modules <- sapply(strsplit(as.character(df$Modules), ',\\s*'), 
                     function(x) toString(sort(x)))
df

#        Date                              Modules
#1 26-11-2021 Advanced chemistry, Biochemistry, NA
#2 25-11-2021         Food chemistry, Food physics

```

**data**

```
df <- structure(list(Date = c("26-11-2021", "25-11-2021"), 
      Modules = c("NA, Advanced chemistry, Biochemistry", 
                   "Food physics, Food chemistry")), 
      row.names = c(NA, -2L), class = "data.frame")

```
We may use `separate_rows` from `tidyr`

```
library(dplyr)
library(tidyr)
df1 %>% 
   separate_rows(Modules, sep = ",\\s*") %>% 
   arrange(Date, Modules) %>%
   group_by(Date) %>% 
   summarise(Modules = toString(Modules))
# A tibble: 2 × 2
  Date       Modules                             
  <chr>      <chr>                               
1 25-11-2021 Food chemistry, Food physics        
2 26-11-2021 Advanced chemistry, Biochemistry, NA

```

### data

```
df1 <- structure(list(Date = c("26-11-2021", "25-11-2021"),
 Modules = c("NA, Advanced chemistry, Biochemistry", 
"Food physics, Food chemistry")), row.names = c(NA, -2L), class = "data.frame")

```