簡體   English   中英

R grep() 和 gsub() :刪除匹配的字符串並包括不匹配的字符串並將所有觀察結果存儲在字符向量中

[英]R grep() and gsub() : remove the matched strings and also include the unmatched strings and store all the observations in a character vector

我有一個數據框transactions

Cust_no  date      debit  credit  comment
1234    12DEC2013      0     100  ATMW XYZ 8974632
1234    11DEC2013    200       0  TFR - XXXX3948389
1543    01DEC2013   3000       0  SAL - CitiBank
1543    02DEC2013      0     800  CHQ TO FAMILY
1543    10DEC2014     10       0  INSURANCE GENERALE
7777    01DEC2014   2500       0  SALARY/01-12-2013/ENJOY

我的目標是從comment列中刪除所有銀行術語、特殊字符和其他不需要的東西,將其存儲在一個變量中並作為新列添加到同一個表中。 所以,我用grep()gsub()

listOfTerms <- ... #the regular expression that contains terms to be removed

NewComment <- gsub(paste(listOfTerms,collapse="|"), " ", transactions[grep(paste(listOfTerms,collapse="|") ,transactions$comment,ignore.case=TRUE),])

但問題是NewComment具有匹配模式的元素,並且它給了我一個Large Character而不是vector

我曾嘗試使用sub()但即便如此,顯然,我得到了相同的輸出。

那么,如果gsub(pattern,grep(...))遇到不匹配的字符串並在一個向量中添加“更正”的行和不匹配的行,我該如何告訴它不要做任何事情? 所需的輸出如下所示。

Cust_no  date      debit  credit  comment                  NewComment
1234    12DEC2013      0     100  ATMW XYZ 8974632         XYZ
1234    11DEC2013    200       0  TFR - XXXX3948389        XXXX
1543    01DEC2013   3000       0  SAL - CitiBank           CitiBank
1543    02DEC2013      0     800  CHQ TO FAMILY            TO FAMILY
1543    10DEC2014     10       0  INSURANCE GENERALE       INSURANCE GENERALE
7777    01DEC2014   2500       0  SALARY/01-12-2013/ENJOY  ENJOY

您可以使用gsub沒有grepgsub將取代該模式匹配的字符串的每個的部分,如果沒有匹配,您將獲得原始字符串。

嘗試:

transactions$NewComment<-gsub(paste(listOfTerms,collapse="|"),"",transactions$comment)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM