2013-02-09 49 views
6

どのように指定した文字まですべての文字を抽出しますか?与えられた例では、 "。"の前にすべてを抽出したいと思います。 (期間):文字列からの文字の抽出

asdasd segssddfge se 

は、私が試した:

substr(a,1,".") 

を動作していないよう

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

私は戻って取得したいと思います。

subを使用して

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

そのcsvファイルを使用して試み「」 – user1234440

答えて

7

はここで非常に基本的なアプローチだ

# 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) 

(のみ1 .がありますと仮定しsubtrgregexprを使用してありますすべてのストライトで明確なマッチベクター内のngs)。

ここ
# 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) 
+1

@Arunは、私のアプローチだった「'固定= true'を」を追加するのを忘れOPのデータに関する(おそらくは間違った)前提に基づいています。ありがとう。 – A5C1D2H2I1M1N2O1R2T1

4

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

別:

2

一つだけがあるはずですので、gsub

gsub(pattern='(.*)[.](.*)','\\1', c("asdasd.sss","segssddfge.sss","se.sss")) 
[1] "asdasd"  "segssddfge" "se"   
関連する問題