我的数据集如下所示
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)
得到""的行
请帮我以任何有效的方式删除它?
一种方法用regex和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"
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)