2015-05-01 5 views
6

stringr पैकेज का उपयोग करके स्ट्रिंग में एकल पैटर्न से मिलान करने वाले कई स्थानों को क्रमशः प्रतिस्थापित करें, वेक्टर किए गए तरीके से रेगेक्स प्रतिस्थापन निष्पादित करना आसान है।अलग-अलग प्रतिस्थापन

प्रश्न:

विभिन्न प्रतिस्थापन, उदा को

hello,world??your,make|[]world,hello,pos 

में हर शब्द को बदलें: मैं निम्न कर सकते हैं कैसे बढ़ती संख्या

1,2??3,4|[]5,6,7 

ध्यान दें कि सरल विभाजक नहीं माना जा सकता है, व्यावहारिक उपयोग केस अधिक जटिल है।


stringr::str_replace_all काम करने के लिए है क्योंकि यह

str_replace_all(x, "(\\w+)", 1:7) 

प्रत्येक प्रतिस्थापन सभी शब्दों के लिए लागू के लिए एक वेक्टर पैदा करता प्रतीत नहीं होता है, या यह अनिश्चित और/या नकली इनपुट प्रविष्टियां हैं ताकि

str_replace_all(x, c("hello" = "1", "world" = "2", ...)) 

उद्देश्य के लिए काम नहीं करेगा।

+1

आप इसके लिए 'gsubfn' पैकेज का उपयोग कर सकते हैं। – hwnd

उत्तर

7

gsubfn का उपयोग करके एक और विचार यहां दिया गया है। pre समारोह प्रतिस्थापन से पहले चलाया जाता है और fun समारोह प्रत्येक खिलाड़ी को बदलने के चलाया जाता है:

library(gsubfn) 
x <- "hello,world??your,make|[]world,hello,pos" 
p <- proto(pre = function(t) t$v <- 0, # replace all matches by 0 
      fun = function(t, x) t$v <- v + 1) # increment 1 
gsubfn("\\w+", p, x) 

कौन देता है:

[1] "1,2??3,4|[]5,6,7" 

यह परिवर्तन के बाद से gsubfn इस्तेमाल के लिए एक count चर का कहना है एक ही जवाब देना होगा आद्य कार्यों में:

pp <- proto(fun = function(...) count) 
gsubfn("\\w+", pp, x) 

उपयोग करने के उदाहरण के लिए gsubfn शब्दचित्र देखें।

+2

बहुत अच्छा जवाब। इन दिनों 'dplyr' के अलावा अन्य कार्यों का उपयोग करके आपको देखकर खुशी हुई;) –

+0

क्या आप प्रतिस्थापन भाग में उपयोग किए गए फ़ंक्शन को समझा सकते हैं? –

3

मैं इस तरह के कुछ के लिए "ore" package का सुझाव दूंगा। विशेष नोट ore.search और ore.subst होगा, जिसके बाद एक फ़ंक्शन प्रतिस्थापन मान के रूप में स्वीकार कर सकता है।

उदाहरण:

library(ore) 

x <- "hello,world??your,make|[]world,hello,pos" 

## Match all and replace with the sequence in which they are found 
ore.subst("(\\w+)", function(i) seq_along(i), x, all = TRUE) 
# [1] "1,2??3,4|[]5,6,7" 

## Create a cool ore object with details about what was extracted 
ore.search("(\\w+)", x, all = TRUE) 
# match: hello world your make world hello pos 
# context:  ,  ?? , |[]  ,  , 
# number: 1==== 2==== 3=== 4=== 5==== 6==== 7== 
1

यहाँ एक आधार आर समाधान। यह भी सदिश होना चाहिए।

x="hello,world??your,make|[]world,hello,pos" 
#split x into single chars 
x_split=strsplit(x,"")[[1]] 
#find all char positions and replace them with "a" 
x_split[gregexpr("\\w", x)[[1]]]="a" 
#find all runs of "a" 
rle_res=rle(x_split) 
#replace run lengths by 1 
rle_res$lengths[rle_res$values=="a"]=1 
#replace run values by increasing number 
rle_res$values[rle_res$values=="a"]=1:sum(rle_res$values=="a") 
#use inverse.rle on the modified rle object and collapse string 
paste0(inverse.rle(rle_res),collapse="") 

#[1] "1,2??3,4|[]5,6,7" 
संबंधित मुद्दे