Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 64 / 68

Testing whether two words are anagrams

This lesson covers testing for anagrams in R, with the aim of understanding how to sort and compare strings.

An anagram is a word made by rearranging the letters of another (listen and silent, for instance). Sort the letters of both and compare.

The sample code lower-cases, splits into single characters, and sorts with sort(strsplit(tolower(a), "")[[1]]), then compares the two sorted results with identical(). "listen" and "silent" have the same letters, so sorted they match.

A common early stumble is the difference between == and identical(). Comparing vectors needs identical(); a plain == returns a vector of element-by-element results.

It is a basic technique for comparing strings while ignoring order. For longer strings, counting how often each character appears is faster.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)