2016-08-16 171 views
1

我正在嘗試向R中的模型公式添加項。如果直接將變量名稱輸入到更新函數中,使用update()會很簡單。但是,如果變量名稱在變量中,則不起作用。在R中使用update()中的變量來更新公式

myFormula <- as.formula(y ~ x1 + x2 + x3) 
addTerm <- 'x4' 

#Works: x4 is added 
update(myFormula, ~ . + x4) 
Output: y ~ x1 + x2 + x3 + x4 

#Does not work: "+ addTerm" is added instead of x4 being removed 
update(myFormula, ~ . + addTerm) 
Output: y ~ x1 + x2 + x3 + addTerm 

通過變量添加x4可以以稍微複雜的方式完成。

formulaString <- deparse(myFormula) 
newFormula <- as.formula(paste(formulaString, "+", addTerm)) 
update(newFormula, ~.) 
Output: y ~ x1 + x2 + x3 + x4 

有沒有辦法讓update()直接做到這一點,而不需要這些額外的步驟?我試過粘貼,解析和其他常用功能,但它們不起作用。

例如,如果使用paste0輸出

update(myFormula, ~ . + paste0(addTerm)) 
Output: y ~ x1 + x2 + x3 + paste0(addTerm) 

有誰知道如何使用更新的變量任何建議()?

感謝

回答

4

你可能只需要做到:

update(myFormula, paste("~ . +",addTerm))