3

我的数据集如下

John
Tally
 mac
hero

我想删除以“”开头的字符串

所以结果变量将是

John
Tally
hero

我用过

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

获取具有“”的行

请帮助我有什么有效的方法来删除它?

4

2 回答 2

8

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" 

或根据@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" 
于 2015-05-20T22:41:34.830 回答
1

使用stringr

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

使用stringi

> vec[!stri_detect(vec, regex = "^\\s")]
# [1] "John"  "Tally" "hero" 
于 2015-05-20T23:33:26.027 回答