如何删除一行,字符串以白色 space 开头?
How to delete a row, having string which start with a white space?
我的数据集如下
John
Tally
mac
hero
我想删除以“”开头的字符串
所以结果变量将是
John
Tally
hero
我用过
library(stringr)
which(startsWith(names[,1]," "))
获取具有“”的行
请帮我删除这个的有效方法?
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"
使用stringr
:
> vec[!str_detect(vec, "^\s")]
# [1] "John" "Tally" "hero"
使用stringi
:
> vec[!stri_detect(vec, regex = "^\s")]
# [1] "John" "Tally" "hero"
我的数据集如下
John
Tally
mac
hero
我想删除以“”开头的字符串
所以结果变量将是
John
Tally
hero
我用过
library(stringr)
which(startsWith(names[,1]," "))
获取具有“”的行
请帮我删除这个的有效方法?
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"
使用stringr
:
> vec[!str_detect(vec, "^\s")]
# [1] "John" "Tally" "hero"
使用stringi
:
> vec[!stri_detect(vec, regex = "^\s")]
# [1] "John" "Tally" "hero"