2014-09-24 21 views
0

我有一个关于在R.一时间产生警告,多个项目,请参考下面的数据帧和代码的问题:R中警告了产生一个以上的项目

数据帧DAT:

inputs var1 var2 
A 1 a 1 
B 2 b 3 
B 3 b NA 
C 4 d NA 
C 5 e 4 

if (any(duplicated(dat$inputs))==T){ 
    warning(paste("The following inputs: ", dat$inputs[duplicated(dat$inputs)],"is duplicated.",sep="")) 
} 

正如你可以看到B和C将在警告中显示,如:

Warning message: 
The following inputs: B is duplicated.The following inputs: C is duplicated. 

我可以接受这样的警告消息输出,但它并不理想。有没有办法将两个句子结合起来,使它看起来像:

Warning message: 
The following inputs: B,C are duplicated. 

非常感谢您的关注和时间。

海伦

+0

看一看'sprintf'和' “%S”'部分 – 2014-09-24 17:50:54

+0

注意'paste'会回收,以适应最长的输入。尝试'粘贴(“测试”,1:5,“再次测试”),看看会发生什么。正如Vlo指出的那样,'collapse'选项就是你要找的。 – Frank 2014-09-24 17:53:42

回答

1

我不能让你的代码运行,所以我做了一些/修改您的代码/数据。

dat = read.table(text = " 
inputs var1 var2 var3 
A 1 a 1 
B 2 b 3 
B 3 b NA 
C 4 d NA 
C 5 e 4", header = T) 


if (any(b<-duplicated(dat$inputs))){ 
    if (length(c<-unique(dat$inputs[b]))>1) {warning(paste0("The following inputs: ", paste0(c, collapse=", "), " are duplicated."))} else 
    {warning(paste0("The following input: ", paste0(c, collapse=", "), " is duplicated."))} 
} 


Warning message: 
The following inputs: B, C are duplicated. 

单重复

dat = read.table(text = " 
inputs var1 var2 var3 
A 1 a 1 
A 2 b 3 
E 3 b NA 
C 4 d NA 
G 5 e 4", header = T) 

Warning message: 
The following input: A is duplicated. 
+0

非常感谢 - 它的工作原理。不知道我可以在另一个内部使用paste()。我还是R的新手。 – Helene 2014-09-24 17:53:52

+0

'any(duplicated(...))'与'anyDuplicated()'是一样的。 – 2014-09-24 18:00:50

相关问题