> startsWith('abc', 'a')
[1] TRUE
> startsWith('abc', 'c')
[1] FALSE
> endsWith('abc', 'a')
[1] FALSE
> endsWith('abc', 'c')
[1] TRUE
问问题
76126 次
6 回答
110
正如在 3.3.0中添加的base
那样,startsWith
(and endsWith
) 就是这样。
> startsWith("what", "wha")
[1] TRUE
> startsWith("what", "ha")
[1] FALSE
https://stat.ethz.ch/R-manual/R-devel/library/base/html/startsWith.html
于 2016-07-01T18:26:06.807 回答
37
不是这样内置的。
选项包括grepl
和substr
。
x <- 'ABCDE'
grepl('^AB', x) # starts with AB?
grepl('DE$', x) # ends with DE?
substr(x, 1, 2) == 'AB'
substr('ABCDE', nchar(x)-1, nchar(x)) == 'DE'
于 2015-07-17T03:10:27.963 回答
14
dplyr 包的select
声明支持starts_with
和ends_with
. 例如,这会选择 iris 数据帧中以Petal
library(dplyr)
select(iris, starts_with("Petal"))
select
也支持其他子命令。试试?select
。
于 2015-07-17T03:14:04.753 回答
11
我能想到的最简单的方法是使用%like%
运算符:
library(data.table)
"foo" %like% "^f"
评估为TRUE
- 以f 开头
"foo" %like% "o$"
评估为- 以oTRUE
结尾
"bar" %like% "a"
评估为TRUE
-包含
于 2016-06-16T15:36:27.393 回答
3
这通过使用 substring 函数相对简单:
> strings = c("abc", "bcd", "def", "ghi", "xyzzd", "a")
> str_to_find = "de"
> substring(strings, 1, nchar(str_to_find)) == str_to_find
[1] FALSE FALSE TRUE FALSE FALSE FALSE
您使用子字符串将每个字符串切割成所需的长度。长度是您在每个字符串的开头查找的字符数。
于 2015-07-17T03:11:10.367 回答
3
dplyr
从包中借用一些代码[see this]你可以这样做:
starts_with <- function(vars, match, ignore.case = TRUE) {
if (ignore.case) match <- tolower(match)
n <- nchar(match)
if (ignore.case) vars <- tolower(vars)
substr(vars, 1, n) == match
}
ends_with <- function(vars, match, ignore.case = TRUE) {
if (ignore.case) match <- tolower(match)
n <- nchar(match)
if (ignore.case) vars <- tolower(vars)
length <- nchar(vars)
substr(vars, pmax(1, length - n + 1), length) == match
}
于 2015-07-17T03:11:39.240 回答