Without regex, you could use
which(nchar(trimws(vec))==0)
The function trimws()
removes trailing and leading whitespace characters from a string. Hence, if after the use of trimws
the length of the string (determined by nchar()
) is not zero, the string contains at least one non-whitespace character.
Example:
vec <- c(" ", "", " "," a ", " ", "b")
which(nchar(trimws(vec))==0)
#[1] 1 2 3 5
The entries 1, 2, 3, and 5 of the vector vec
are either empty or contain only whitespace characters.
As suggested by Richard Scriven, the same result can be obtained without calling nchar()
, by simply using trimws(vec)==""
(or which(trimws(vec)=="")
, depending on the desired output: the former results in a vector of booleans, the latter in the index numbers of the blank/empty entries).