2017-08-17 112 views
3

這似乎是一個簡單的問題,但我找不到答案。我有一個包含調用參數名稱的字符向量。在函數中,如果其中一些錯誤,我想提出警告,並引用名稱。警告中引用名稱

bad = c("a", "b", "c") 
warning(paste("Variables", paste(bad, collapse = ", "), "are wrong")) 

這給:

Warning message: 
Variables a, b, c are wrong 

,但我需要:

Warning message: 
Variables 'a', 'b', 'c' are wrong 

我想做到這一點,而無需使用外部包。

回答

8

我們可以使用ASCII撇號他\'

warning(paste("Variables", paste0("\'", bad, "\'", collapse = ", "), "are wrong")) 

# Warning message: 
# Variables 'a', 'b', 'c' are wrong 

或單引號由sQuote

warning(paste("Variables", paste(sQuote(bad), collapse = ", "), "are wrong")) 

# Warning message: 
# Variables ‘a’, ‘b’, ‘c’ are wrong 

或雙引號通過dQuote

warning(paste("Variables", paste(dQuote(bad), collapse = ", "), "are wrong")) 

# Warning message: 
# Variables 「a」, 「b」, 「c」 are wrong 
+0

這是整齊的,但我不會用在左/右報價警告。但是,我根本不會添加引號。 – Roland

+0

@Roland謝謝你,編輯我的答案,但是,用法取決於用戶。 –

1

這是你在找什麼?

bad = c("'a'", "'b'", "'c'") 
warning(paste("Variables", paste(bad, collapse = ", "), "are wrong")) 

,如果你想節省一些打字,你可以寫類似

quotify <- function(x) paste0("'", x, "'") 

bad = quotify(c("a", "b", "c")) 
warning(paste("Variables", paste(bad, collapse = ", "), "are wrong")) 
4

您可以使用此方法:

warning("Variables ", paste0("'", bad, "'", collapse = ", "), " are wrong") 
# Warning message: 
# Variables 'a', 'b', 'c' are wrong 

替代版本爲雙引號:

warning("Variables ", paste0("\"", bad, "\"", collapse = ", "), " are wrong") 
# Warning message: 
# Variables "a", "b", "c" are wrong