Alphabetically sorting your source code character vectors

Neat little tricks, Episode 1

neat-tricks
Author

Philipp Kollenda

Published

August 17, 2022

A productive rabbit hole

For week 33 of #TidyTuesday 2022 I had to manually select names from a dataset. So, I typed something like

filter(df, name %in% c("The Witcher", "Hamilton", "Westworld", "Sense8"))

Do you see what’s wrong with this? No? Congratulations 🎉, you have a much healthier, more pragmatic approach to coding than I do.

I, on the other hand, was bothered by the fact that the series names were not in alphabetical order. But, “hey”, I thought, R is a “well-developed, simple and effective programming language”, so why not use it to bring my source code into alphabetical order.

Obviously, I could just type my input in alphabetical order, but where is the fun in that?

The context is not really important, so I won’t go into detail on what this dataset was about. The trick is super generally and applies to many situations anyways. But you can see my final plot on Twitter and the accompanying blog post on my website.

How to programatically sort your source code into alphabetical order.

My goal is to get alphabetically sorted output that I can simply copy + paste into my source file (or write to the file with write_lines()).

x <- c("The Witcher", "Hamilton", "Westworld", "Sense8")
print(x)
[1] "The Witcher" "Hamilton"    "Westworld"   "Sense8"     
dput(sort(x))
c("Hamilton", "Sense8", "The Witcher", "Westworld")

Success! That last line is something I can copy. 😃 And…it only took approximately 1000 hours of googling to find dput() 🙈 Eventually the Similar questions that pop-up just before you create a stackoverflow question came to the rescue.

It would be really cool to immediately copy the output of the dput() statement to the clipboard. There is the clipr package which looks promising, but that is something for another evening.