如何删除一行,其中包含以空格开头的字符串?

时间:2015-05-20 22:36:24

标签: r stringr

我的数据集如下所示

John
Tally
 mac
hero

我想删除以&#34开头的字符串; "

所以结果变量是

John
Tally
hero

我用过

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

获取行" "

请帮我以任何有效的方式删除它?

2 个答案:

答案 0 :(得分: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" 

答案 1 :(得分:1)

使用stringr

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

使用stringi

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