2015-07-17 7 views

risposta

37

io non so esattamente quando è stato aggiunto al base (almeno dal 3.3.0), ma startsWith (e endsWith) sono esattamente questo.

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

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

+2

Grazie, ijoseph, per favore vedi il commento di alexis_laz sotto la risposta accettata. – Chen

+0

@Chen - Penso che appartenga ancora come risposta, dal momento che è ciò che cercavi in ​​origine. I commenti non sono scolpiti nella pietra. –

+0

@Quindi ah, ho completamente perso quel commento prima. – ijoseph

17

Non integrato in questo modo.

Le opzioni includono grepl e 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' 
+9

(solo una nota) Da R 3.3.0, le funzioni ' startsWith' e 'endsWith' esistono. –

3

Questo è relativamente semplice utilizzando la funzione 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 

si taglia ogni stringa alla lunghezza desiderata con stringa. La lunghezza è il numero di caratteri che stai cercando all'inizio di ogni stringa.

3

Prendendo in prestito un certo codice dal pacchetto dplyr[see this] si potrebbe fare qualcosa di simile:

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 
} 
8

select La dichiarazione del pacchetto dplyr supporta starts_with e ends_with. Ad esempio, questo seleziona le colonne della cornice dati iride che si aprono con Petal

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

select supporta anche altri comandi. Prova ?select.

+0

è logico ritorno –

3

Il modo più semplice che posso pensare è quello di utilizzare il %like% dell'operatore:

library(data.table) 

"foo" %like% "^f" 

valuta come TRUE - A partire da f

"foo" %like% "o$" 

valuta come TRUE - Termina con o

"bar" %like% "a" 

valuta come TRUE - contenenti un

Problemi correlati