How can I delete a line that has a line that starts with a space?

my dataset looks like this

John
Tally
 mac
hero

      

I want to delete a line that starts with ""

so the resulting variable will be

John
Tally
hero

      

I used

library(stringr)
which(startsWith(names[,1]," "))

      

to get lines with ""

Please help me in an efficient way to remove this?

+3


source to share


2 answers


One way with regex

and grepl

:

vec <- c('John',
         'Tally',
         ' mac',
         'hero')

 #grepl returns TRUE if there is a match.
 #'^ ' is regex for 'starting with space'
  > vec[!grepl('^ ', vec)]
[1] "John"  "Tally" "hero" 

      

Or as per @NealFultz comment:

> vec[grep('^ ', vec, invert=TRUE)]
[1] "John"  "Tally" "hero"

> grep('^ ', vec, invert=TRUE, value=TRUE)
[1] "John"  "Tally" "hero" 

      



Or, if you want to use startsWith

:

library(gdata)
#notice the minus sign below just before which
> vec[-which(startsWith(vec," "))]
[1] "John"  "Tally" "hero" 

      

or simply (as per @ Gregor's comment):

> vec[!startsWith(vec, " ")]
[1] "John"  "Tally" "hero" 

      

+8


source


Usage stringr

:

> vec[!str_detect(vec, "^\\s")]
# [1] "John"  "Tally" "hero" 

      



Usage stringi

:

> vec[!stri_detect(vec, regex = "^\\s")]
# [1] "John"  "Tally" "hero" 

      

+1


source







All Articles