2014-09-24 56 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

相關問題