parse函数将code转化为表达式:“expression”,然后eval函数又可以执行parse函数处理后的“expression”
举个例子
b <- "
for (i in 1:5) {
print(i)
}
"
parsed_b <- parse(text = b)
class(parsed_b)
# [1] "expression"
eval(parsed_b)
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
用于计算表达式格式的字符串
a=c("2/5","4/5")
eval(parse(text = a[1]))
#如果有一列批量的表达式格式的字符串,可以使用apply或map系列函数循环
purrr::map_dbl(a,~eval(parse(text = (.x))))
#[1] 0.4 0.8
回归函数LM中使用
lm_func <- function(var) {
lm( wt~ var, data = mtcars)
}
lm_func(mpg)
#Error in model.frame.default(formula = wt ~ var, data = mtcars, drop.unused.levels = TRUE) :
#invalid type (list) for variable 'var'
这里可以和我之前的https://www.yuque.com/jingjing-ohrxq/poi2hf/pzax0g[dplyr编程,quote与unquote],进行联动。之前包含tidyverse语法的函数写函数的时候,我们提到需要进行“引用”和“反引用”,同时,这里在LM函数中,也遇到了类似的情况
这里查阅帮助可知,lm函数的第一个参数为formula,
# lm(formula = , data = )
因此,我们可以使用parse函数和eval函数将字符串形式的”wt ~ mpg”转换为formula,再带入lm函数后可以正确运行
lm_func <- function(var) {
lm(eval(parse(text = paste0("wt ~ ", var))), data = mtcars)
}
lm_func('mpg')
#除了使用parse函数和eval函数,另一种方法是使用formula函数将字符串"wt ~ mpg"直接转换为formula
lm_func <- function(var) {
lm(formula(paste0("wt ~ ", var)), data = mtcars)
}
lm_func('mpg')
绘图函数ggplot中
使用mtcars数据集,以wt为因变量,欲分别绘制mpg、cyl、disp、hp、drat与wt的散点图
plot_func <- function(var) {
ggplot(data = mtcars, aes(x = var, y = wt)) +
geom_point() +
labs(x = var, y = "wt") +
theme_bw()
}
plot_func(var = mpg)
plot_func(var = "mpg")
#Don't know how to automatically pick scale for object of type tbl_df/tbl/data.frame.
#Defaulting to continuous.
使用eval(parse())
ggplot(data = mtcars, aes(x = eval(parse(text = "mpg")),
y = eval(parse(text = "wt")))) +
geom_point() +
labs(x = "mpg", y = "wt") +
theme_bw()
plot_func(var = "mpg")
另一种方法:ggplot函数参数中,将aes改为aes_string可以正确处理字符串对象
plot_func <- function(var) {
ggplot(data = mtcars, aes_string(x = var, y = "wt")) +
geom_point() +
labs(x = var, y = "wt") +
theme_bw()
}
plot_func(var = "mpg")
最近又看到了substitute+eval的用法
library(survival)
t.test2 <- function(x,y,data){
x = substitute(x)
y = substitute(y)
t.test(eval(y)~eval(x),data)
}
t.test2(sex,ph.karno,lung)
## Welch Two Sample t-test
## data: eval(y) by eval(x)
## t = -0.17097, df = 191.23, p-value = 0.8644
## alternative hypothesis: true difference in means between group 1 and group 2 is not equal to 0
## 95 percent confidence interval:
## -3.589164 3.016577
## sample estimates:
## mean in group 1 mean in group 2
## 81.82482 82.11111