> startsWith('abc', 'a')
[1] TRUE
> startsWith('abc', 'c')
[1] FALSE
> endsWith('abc', 'a')
[1] FALSE
> endsWith('abc', 'c')
[1] TRUE
> startsWith('abc', 'a')
[1] TRUE
> startsWith('abc', 'c')
[1] FALSE
> endsWith('abc', 'a')
[1] FALSE
> endsWith('abc', 'c')
[1] TRUE
作为在3.3.0版本中添加到base
的一部分,startsWith
(以及endsWith
)正是这个意思。
> startsWith("what", "wha")
[1] TRUE
> startsWith("what", "ha")
[1] FALSE
https://stat.ethz.ch/R-manual/R-devel/library/base/html/startsWith.html
startsWith(x, prefix)
和endsWith(x, suffix)
。”来自R更改日志https://cran.r-project.org/doc/manuals/r-devel/NEWS.html - Frank不是内置的那样。
选项包括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'
startsWith
和 endsWith
存在。 - alexis_lazdplyr包的select
语句支持starts_with
和ends_with
。例如,这会选择以Petal
开头的鸢尾花数据框的列。
library(dplyr)
select(iris, starts_with("Petal"))
select
还支持其他子命令。尝试使用 ?select
。
我能想到的最简单方法就是使用 %like%
运算符:
library(data.table)
"foo" %like% "^f"
评估为TRUE
- 以f开头
"foo" %like% "o$"
评估为TRUE
- 以o结尾
"bar" %like% "a"
评估为 TRUE
- 包含a
> 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
使用substring函数可以把每个字符串剪切到所需的长度。要剪切的长度即为你需要在每个字符串开头寻找的字符数。
从 dplyr
包[请参考此链接] 借用一些代码,您可以像这样操作:
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
}
iris[grepl("^Petal",names(iris))]
。 - thelatemail