2013-10-21 74 views
4

我是使用R的新手,我在使用gsub正確格式化我的列表時遇到問題。我需要做兩個替換。R gsub返回不正確的數據

  • 首先更換更換所有@@mydomain.com
  • 二替換空值替換所有www.後。

更新

我目前正在運行gsub兩次,並用我的代碼它的工作原理校正。我有太多的gsub實例,我沒有看到。

vec <- c('[email protected]', '[email protected]', '[email protected]', 
     '[email protected]', 'www.google.com', 'www.gmail.com', 
     'www.domain.com', 'www.example.com') 

vec <- gsub("@.*\\.com", "@mydomain.com", vec) 
vec <- gsub("www\\.", "", vec) 

print(vec) 

更新

但我想運行gsub一個實例都在同一時間,如果可能還是更換。

+1

創建矢量你沒有指定第一個'gsub'調用的結果任何事情。 – joran

+0

你可以嵌套它:'vec < - gsub(「www \\。」,「」,gsub(「@。* \\ .com」,「@ example.com」,vec))''。 –

+0

它在我的代碼 –

回答

4

我已經做到了這一點,您可以將您的gsub功能級聯在一起。

vec <- gsub('@[^.]*\\.[^.]*', '@mydomain.com', gsub('www\\.', '', vec)) 
print(vec) 

另一種解決方案是爲您old valuesreplacement values

re <- c('@[^.]*\\.[^.]*', 'www\\.') 
val <- c('@mydomain.com', '') 

recurse <- function(pattern, repl, x) { 
    for (i in 1:length(pattern)) 
     x <- gsub(pattern[i], repl[i], x) 
     x 
} 

vec <- c('[email protected]', '[email protected]', '[email protected]', 
     '[email protected]', 'www.google.com', 'www.gmail.com', 
     'www.domain.com', 'www.example.com') 

print(recurse(re, val, vec)) 

輸出

"[email protected]"   "[email protected]"   
"[email protected]"  "[email protected]" 
"google.com"     "gmail.com"     
"domain.com"     "example.com"  
+0

我喜歡你所做的遞歸功能。 –