UFO ET IT

R에는 Python과 같은 startswith 또는 endswith 기능이 있습니까?

ufoet 2020. 12. 3. 21:09
반응형

R에는 Python과 같은 startswith 또는 endswith 기능이 있습니까?


질문은 제목에서 매우 명확합니다.


으로 추가 base3.3.0에서 , 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


그렇게 내장되어 있지 않습니다.

옵션에는 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'

dplyr 패키지의 select문은 starts_withends_with. 예를 들어, 다음으로 시작하는 홍채 데이터 프레임의 열을 선택합니다.Petal

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

select다른 하위 명령도 지원합니다. 시도해보십시오 ?select.


내가 생각할 수있는 가장 간단한 방법은 %like%연산자 를 사용하는 것 입니다.

library(data.table)

"foo" %like% "^f" 

다음으로 평가 -f로TRUE 시작

"foo" %like% "o$" 

다음으로 평가 -oTRUE끝남

"bar" %like% "a"

로 평가하여 TRUE포함하는 -


로부터 몇 가지 코드를 차용 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
}

하위 문자열 함수를 사용하면 비교적 간단합니다.

> 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

하위 문자열을 사용하여 각 문자열을 원하는 길이로 자릅니다. 길이는 각 문자열의 시작 부분에서 찾고있는 문자 수입니다.

참고 URL : https://stackoverflow.com/questions/31467732/does-r-have-function-startswith-or-endswith-like-python

반응형