I have the following sample data:

target <- "Stackoverflow"
candidates <- c("Stackflow", "Stackflow", "Stckoverfow")

I would like to filter the string from candidates that has the lowest (levensthein) distance to the target string.

I decided to use the pipe operator to improve readability. However, i find it suboptimal that adist doesnt return the strings that corresponds to the distances.

My attempts:

Version 1)

candidates  %>%  
  adist(y = target) %>% 
  which.min %>% 
  `[`(x = candidates, i = .)

Version 2)

candidates %>% 
  adist(y = target) %>% 
  data.frame(dist = ., candidates = candidates) %>% 
  filter(dist == min(dist)) %>% select(candidates)


I want to Improve readability. Memory usage or performance do not matter as data is pretty small. Using additional packages, like dplyr, is also fine.

In version 1 i think `[`(...) is bad to read.

Version 2 seems better to me. But it does not seem optimal to me, that i have to add the strings to the data.frame after having applied adist() to them: data.frame(dist = ., candidates = candidates).


1 Answer 1


What is wrong with simple code like?:

distances <- adist(candidates, target)
candidates[distances == min(distances)]

This is shorter and, in my opinion, easier to read, as it do not require any knowledge of additional packages.

Also, you mentioned that your data is small and it looks like you are working with vectors, in that case I do not see a point to use data.frame, dplyr etc.

  • \$\begingroup\$ hmm...:) Ileft out some preprocessing steps in the question (which let me choose to go for pipes). But yeah, given me question this is far easier :) Thanks. \$\endgroup\$ Oct 23, 2019 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.