Does R have function startswith or endswith like python?

PythonRStringStartswithEnds With

Python Problem Overview


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

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

Python Solutions


Solution 1 - Python

As added to base in 3.3.0, startsWith (and endsWith) are exactly this.

> startsWith("what", "wha")
[1] TRUE
> startsWith("what", "ha")
[1] FALSE

https://stat.ethz.ch/R-manual/R-devel/library/base/html/startsWith.html

Solution 2 - Python

Not inbuilt like that.

Options include grepl and 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'

Solution 3 - Python

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

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

select supports other subcommands too. Try ?select .

Solution 4 - Python

The simplest way I can think of is to use the %like% operator:

library(data.table)

"foo" %like% "^f" 

evaluates as TRUE - Starting with f

"foo" %like% "o$" 

evaluates as TRUE - Ending with o

"bar" %like% "a"

evaluates as TRUE - Containing a

Solution 5 - Python

This is relatively simple by using the substring function:

> 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.

Solution 6 - Python

Borrowing some code from the dplyr package [see this] you could do something like 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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjarviView Question on Stackoverflow
Solution 1 - PythonijosephView Answer on Stackoverflow
Solution 2 - Pythonmathematical.coffeeView Answer on Stackoverflow
Solution 3 - PythonG. GrothendieckView Answer on Stackoverflow
Solution 4 - PythonDaniGateView Answer on Stackoverflow
Solution 5 - PythonMaxime BietteView Answer on Stackoverflow
Solution 6 - PythonJasonAizkalnsView Answer on Stackoverflow