adR
adR

Reputation: 325

Remove empty strings from named vector in R

Does anyone know how to remove an empty string from the named vector? I tried the following but could not get what I wanted.

X <- c('a', NA, '', 'b')
names(X) <- rep("d",4)

then I applied one the stringi function as fallow

stringi::stri_remove_empty(names(X)) # it return this  "a" NA  "b"
stringi::stri_remove_empty(X) # it return just the names "d" "d" "d" "d"

But actually I want get as following

 d   d   d
"a" "na" "b" 

appreciate your help

best adr

Upvotes: 1

Views: 434

Answers (1)

akrun
akrun

Reputation: 887881

We may use nzchar from base R to create a logical expression i.e. TRUE for non-blank and FALSE for blank ("")

X[nzchar(X)]
d   d   d 
"a"  NA "b" 

If we want to remove both missing (NA) and blank

X[nzchar(X) & complete.cases(X)]
  d   d 
"a" "b" 

Upvotes: 3

Related Questions