How to use stringr functions to remove all empty words?

Viewed 60
b <- c("books",  "  ",  "animals",  "frogs")

#My code: 
b[!grepl("^\\s+$", b)]
[1] "books"   "animals" "frogs"   

#Now, I am working to figure out this solution with stringr package.
str_remove_all(b, "^\\s+$")
[1] "books"   ""          "animals" "frogs" 

The output shows "" where my new code fails. Any solution to get the result like my first code?

3 Answers

We may use str_subset in stringr

library(stringr)
str_subset(b, "^\\s+$", negate = TRUE)
[1] "books"   "animals" "frogs"  

The function that corresponds to grepl is str_detect

b[str_detect(b, "^\\s+$", negate = TRUE)]
[1] "books"   "animals" "frogs" 

In base R, we may use grep with invert = TRUE

grep("^\\s+$", b, invert = TRUE, value = TRUE)
[1] "books"   "animals" "frogs"  

Or without regex with trimws (to remove the spaces - leading/lagging) and use nzhcar to create logical vector for subsetting

b[nzchar(trimws(b))]
[1] "books"   "animals" "frogs"  

Two base R alternatives:

b[nzchar(trimws(b))]
# [1] "books"   "animals" "frogs"  
b[grepl("\\S",b)]
# [1] "books"   "animals" "frogs"  

In base R we can do:

b[b !=" "]

Output:

[1] "books"   "animals" "frogs" 

OR with stringr:

library(stringr)
str_subset(str_squish(b), "")
[1] "books"   "animals" "frogs" 
Related