2015-05-20 48 views

回答

8

一種方式與regexgrepl

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" 

或每@NealFultz的評論爲:

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

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

或者,如果你想使用startsWith

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

或簡單地(根據@Gregor的評論):

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

參見'grep的(...,反轉= TRUE)' –

+0

@NealFultz酷!謝謝,今天學到了新東西! – LyzandeR

+0

np。另請參閱'grep(...,value = TRUE)',您可以將它歸結爲一個函數調用。 –

1

使用stringr

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

使用stringi

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