R 是否有像 python 一样的函数开始或结束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31467732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does R have function startswith or endswith like python?
提问by user4015990
> startsWith('abc', 'a')
[1] TRUE
> startsWith('abc', 'c')
[1] FALSE
> endsWith('abc', 'a')
[1] FALSE
> endsWith('abc', 'c')
[1] TRUE
采纳答案by ijoseph
As added to base
in 3.3.0, startsWith
(and endsWith
) are exactly this.
正如在 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
https://stat.ethz.ch/R-manual/R-devel/library/base/html/startsWith.html
回答by mathematical.coffee
Not inbuilt like that.
不是那样内置的。
Options include grepl
and substr
.
选项包括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'
回答by Maxime Biette
This is relatively simple by using the substring function:
通过使用 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
You cut each string to the desired length with substring. The length being the number of characters you are looking for at the beginning of each string.
您可以使用子字符串将每个字符串剪切到所需的长度。长度是您在每个字符串开头查找的字符数。
回答by JasonAizkalns
Borrowing some code from the dplyr
package [see this]you could do something like this:
从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
}
回答by G. Grothendieck
The dplyr package's select
statement supports starts_with
and ends_with
. For example, this selects the columns of the iris data frame that start with Petal
dplyr 包的select
声明支持starts_with
和ends_with
。例如,这将选择 iris 数据框的列以Petal
library(dplyr)
select(iris, starts_with("Petal"))
select
supports other subcommands too. Try ?select
.
select
也支持其他子命令。试试?select
。
回答by DaniGate
The simplest way I can think of is to use the %like%
operator:
我能想到的最简单的方法是使用%like%
运算符:
library(data.table)
"foo" %like% "^f"
evaluates as TRUE
- Starting with f
评估为TRUE
- 以f 开头
"foo" %like% "o$"
evaluates as TRUE
- Ending with o
评估为TRUE
- 以o结尾
"bar" %like% "a"
evaluates as TRUE
- Containing a
作为计算TRUE
-包含一个