R语言中是否有类似Python的startswith或endswith函数?

93
> startsWith('abc', 'a')
[1] TRUE
> startsWith('abc', 'c')
[1] FALSE

> endsWith('abc', 'a')
[1] FALSE  
> endsWith('abc', 'c')
[1] TRUE

9
你可以使用正则表达式,例如 iris[grepl("^Petal",names(iris))] - thelatemail
6个回答

135

2
谢谢,ijoseph,请查看已接受答案下alexis_laz的评论。 - user2165
@Chen - 我认为这仍然应该作为一个答案,因为这正是你最初寻找的。评论并不是铁板一块。 - Rich Scriven
1
@陈啊,我之前完全没看到那个评论。 - ijoseph
2
它在3.3.0中被添加:“新的字符串实用程序startsWith(x, prefix)endsWith(x, suffix)。”来自R更改日志https://cran.r-project.org/doc/manuals/r-devel/NEWS.html - Frank
更新以增加确定性。感谢您的调查,@FrankPinter。 - ijoseph
1
相关:tidyverse软件包使此功能可用 -str_starts('abc', 'ab' ) # TRUE - Michael

41

不是内置的那样。

选项包括greplsubstr

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'

19
自 R 3.3.0 起,函数 startsWithendsWith 存在。 - alexis_laz

14

dplyr包的select语句支持starts_withends_with。例如,这会选择以Petal开头的鸢尾花数据框的列。

library(dplyr)
select(iris, starts_with("Petal"))

select 还支持其他子命令。尝试使用 ?select


starts_with() 函数用于选择列,不是行! - Michael
@Michael,这与选择行无关。 - G. Grothendieck

12

我能想到的最简单方法就是使用 %like% 运算符:

library(data.table)

"foo" %like% "^f" 

评估为TRUE - 以f开头

"foo" %like% "o$" 

评估为TRUE - 以o结尾

"bar" %like% "a"

评估为 TRUE - 包含a


3
这可以通过使用子字符串函数来实现:
> 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函数可以把每个字符串剪切到所需的长度。要剪切的长度即为你需要在每个字符串开头寻找的字符数。


3

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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接