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?
CodePudding user response:
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")
CodePudding user response:
you could use order i guess?
v<-c("Z","X","Y","A","B","C")
df<-data.frame(1:6,v)
> df[order(df$v),]
X1.6 v
4 4 A
5 5 B
6 6 C
2 2 X
3 3 Y
1 1 Z