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

Ama*_*eet 3 r stringr

我的数据集如下所示

John
Tally
 mac
hero
Run Code Online (Sandbox Code Playgroud)

我想删除以""开头的字符串

所以结果变量是

John
Tally
hero
Run Code Online (Sandbox Code Playgroud)

我用过

library(stringr)
which(startsWith(names[,1]," "))
Run Code Online (Sandbox Code Playgroud)

得到""的行

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

Lyz*_*deR 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" 
Run Code Online (Sandbox Code Playgroud)

或者根据@NealFultz的评论:

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

> grep('^ ', vec, invert=TRUE, value=TRUE)
[1] "John"  "Tally" "hero" 
Run Code Online (Sandbox Code Playgroud)

或者如果你想使用startsWith:

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

或者简单地(根据@Gregor的评论):

> vec[!startsWith(vec, " ")]
[1] "John"  "Tally" "hero" 
Run Code Online (Sandbox Code Playgroud)

  • See also `grep(..., invert=TRUE)` (2认同)
  • 另外,这是不必要的,`vec [!startsWith(vec,"")]` (2认同)