Ibrahimli
Ibrahimli

Reputation: 221

How to use stringr functions to remove all empty words?

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?

Upvotes: 5

Views: 65

Answers (3)

TarJae
TarJae

Reputation: 79184

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" 

Upvotes: 1

r2evans
r2evans

Reputation: 160687

Two base R alternatives:

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

Upvotes: 2

akrun
akrun

Reputation: 887691

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"  

Upvotes: 3

Related Questions