替换 R 公式中的字符串
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
在执行替换时查找环境中的变量,这意味着它总是尝试替换公式中的 names。有没有办法替换字符 'a'?
在 base 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)
我对 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
在执行替换时查找环境中的变量,这意味着它总是尝试替换公式中的 names。有没有办法替换字符 'a'?
在 base 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)