5
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?

1
  • b[nzchar(trimws(b))] Commented Oct 17, 2021 at 19:49

3 Answers 3

3

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"  
Sign up to request clarification or add additional context in comments.

Comments

2

Two base R alternatives:

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

Comments

1

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" 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.