Consider the old code posted by @davharris and this example here https://github.com/gagern/RePairs/blob/master/RePairs.R