2013-02-09 29 views
6

Come estrarre tutti i caratteri fino a un carattere specificato? Ad esempio, vorrei estrarre tutto prima del "." (Punto):Estrazione caratteri da stringa

a<-c("asdasd.sss","segssddfge.sss","se.sss") 

Vorrei tornare:

asdasd segssddfge se 

ho provato:

substr(a,1,".") 

ma non sembra funzionare.

qualche idea?

+0

il suo un file CSV quindi ci dovrebbe essere un solo "" – user1234440

risposta

7

Ecco un approccio molto semplice:

sapply(strsplit(a, "\\."), `[[`, 1) 
# [1] "asdasd"  "segssddfge" "se" 

E un altro:

sub(".sss", "", a, fixed = TRUE) 
# [1] "asdasd"  "segssddfge" "se" 
## OR sub("(.*)\\..*", "\\1", a) 
## And possibly other variations 
+1

@Arun, ha dimenticato di aggiungere "' fisso = TRUE" che è stato l'approccio che ho stava prendendo basati su ipotesi (forse errate) sui dati del PO. Grazie. – A5C1D2H2I1M1N2O1R2T1

4

Utilizzando sub:

# match a "." (escape with "\" to search for "." as a normal "." 
# means "any character") followed by 0 to any amount of characters 
# until the end of the string and replace with nothing ("") 
sub("\\..*$", "", a) 

Utilizzando subtr e gregexpr (supponendo che c'è solo 1 . e c'è un partita definitiva in tutti gli stri ng all'interno del vettore).

# get the match position of a "." for every string in "a" (returns a list) 
# unlist it and get the substring of each from 1 to match.position - 1 
substr(a, 1, unlist(gregexpr("\\.", a)) - 1) 
2

Ecco un tentativo utilizzando gsub

gsub(pattern='(.*)[.](.*)','\\1', c("asdasd.sss","segssddfge.sss","se.sss")) 
[1] "asdasd"  "segssddfge" "se"