1
$\begingroup$

I have a huge string in R where I want to remove single characters from. So for example, the string might be

blabla a test this that b á

And the result should be

blabla test this that

How do I do this in R?

$\endgroup$
1
  • $\begingroup$ please accept an answer if it worked for you! $\endgroup$
    – Stereo
    Feb 27, 2017 at 9:05

1 Answer 1

2
$\begingroup$

This splits the string and filters the substrings by length, no regex:

string <- "blabla a test this that b á"
paste(Filter(function(x) nchar(x) > 1,
             unlist(strsplit(string, " "))), 
      collapse=" ")
# [1] "blabla test this that"

(does not work with multiple space characters)

$\endgroup$
2
  • 1
    $\begingroup$ You might get it to work with multiple space characters by using strsplit(string, "\\W+", perl=TRUE). That should enable perl regex matching and then split based on one or more whitespace characters. $\endgroup$
    – Duncan
    Feb 16, 2017 at 1:40
  • $\begingroup$ If you want to split on multiple spaces, you can also just use '\\s+' as split. $\endgroup$
    – Jaap
    Mar 4, 2017 at 10:30

Your Answer

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

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