一種方法的作品,雖然有點繁瑣,更換運營商$
等與變量名合法字符,把字符串返回到一個公式,適用all.vars
,並取消裂傷結果:
All.vars = function(expr, retain = c("\\$", "\\[\\[", "\\]\\]"), ...) {
# replace operators with unlikely patterns _Av1_, _Av2_, ...
repl = paste("_Av", seq_along(retain), "_", sep = "")
for (i in seq_along(retain))
expr = gsub(retain[i], repl[i], expr)
# piece things back together in the right order, and call all.vars
subs = switch(length(expr), 1, c(1,2), c(2,1,3))
vars = all.vars(as.formula(paste(expr[subs], collapse = "")), ...)
# reverse the mangling of names
retain = gsub("\\\\", "", retain) # un-escape the patterns
for (i in seq_along(retain))
vars = gsub(repl[i], retain[i], vars)
vars
}
使用retain
參數指定我們希望保留的模式,而不是作爲運算符對待。默認值是$
,[[
和]]
(所有正式轉義)下面是一些結果:
> form = log(cows$weight) ~ factor(bulls[[3]]) * herd$breed
> All.vars(form)
[1] "cows$weight" "bulls[[3]]" "herd$breed"
變化retain
也包括(
和)
:
> All.vars(form, retain = c("\\$", "\\(", "\\)", "\\[\\[", "\\]\\]"))
[1] "log(cows$weight)" "factor(bulls[[3]])" "herd$breed"
的點傳遞到all.vars
,這與all.names
確實相同,但具有不同的默認值。因此,我們也能獲得的功能和運營商不retain
:
> All.vars(form, functions = TRUE)
[1] "~" "log" "cows$weight" "*"
[5] "factor" "bulls[[3]]" "herd$breed"
那麼,帶有'$'和'[[''的公式是非常有問題的工作,真的應該避免。你認爲他們有必要的情景是什麼?如果我有'〜x [[y]]'和'y < - 「p」'怎麼辦?這個函數返回什麼? – MrFlick
我同意他們應該避免。但我是一名軟件包開發人員,一些用戶會像我說明的那樣適合模型(儘管通常不是那麼極端)。 – rvl