2013-10-21 72 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

我喜欢你所做的递归功能。 –