我的数据集如下所示
John
Tally
mac
hero
我想删除以&#34开头的字符串; "
所以结果变量是
John
Tally
hero
我用过
library(stringr)
which(startsWith(names[,1]," "))
获取行" "
请帮我以任何有效的方式删除它?
答案 0 :(得分:8)
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"
或者根据@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"