[英]Replacing a string in an R formula
我對R中的公式修改有疑問。
可以說我有一個公式。
> fo <- a ~ b + c
我可以使用substitute_q
替換術語
> pryr::substitute_q(fo, list(a = 'happy'))
"happy" ~ b + c
如果要替換不帶引號的術語,可以將其替換為名稱
> pryr::substitute_q(fo, list(a = as.name('happy')))
happy ~ b + c
但是,現在讓我們說我有一個帶字符串的公式。
> fo <- 'a' ~ b + c
> fo
"a" ~ b + c
我找不到從公式中替換字符串的方法。
> pryr::substitute_q(fo, list(a = as.name('happy')))
"a" ~ b + c
> pryr::substitute_q(fo, list("a" = as.name('happy')))
"a" ~ b + c
> pryr::substitute_q(fo, list(`"a"` = as.name('happy')))
"a" ~ b + c
> pryr::substitute_q(fo, list('"a"' = as.name('happy')))
"a" ~ b + c
我認為這是因為substitute_q
在執行替換時會在環境中查找變量,這意味着它始終嘗試替換公式中的名稱 。 有沒有辦法替換字符“ a”?
在基數R中,使用deparse
將公式轉換為字符,執行必要的替換,然后強制返回公式
fo <- 'a' ~ b + c
as.formula(gsub("\"a\"", "\"happy\"", deparse(fo)))
#"happy" ~ b + c
fo2 = func1(a, b) ~ func2("e", 10) + b * c + func3(d)
as.formula(gsub("func2(\"e\", 10)", "func2(HAN, SOLO)", deparse(fo2), fixed = TRUE))
#func1(a, b) ~ func2(HAN, SOLO) + b * c + func3(d)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.