parse函数将code转化为表达式:“expression”,然后eval函数又可以执行parse函数处理后的“expression”

举个例子

  1. b <- "
  2. for (i in 1:5) {
  3. print(i)
  4. }
  5. "
  6. parsed_b <- parse(text = b)
  7. class(parsed_b)
  8. # [1] "expression"
  9. eval(parsed_b)
  10. # [1] 1
  11. # [1] 2
  12. # [1] 3
  13. # [1] 4
  14. # [1] 5

用于计算表达式格式的字符串

  1. a=c("2/5","4/5")
  2. eval(parse(text = a[1]))
  3. #如果有一列批量的表达式格式的字符串,可以使用apply或map系列函数循环
  4. purrr::map_dbl(a,~eval(parse(text = (.x))))
  5. #[1] 0.4 0.8

回归函数LM中使用

  1. lm_func <- function(var) {
  2. lm( wt~ var, data = mtcars)
  3. }
  4. lm_func(mpg)
  5. #Error in model.frame.default(formula = wt ~ var, data = mtcars, drop.unused.levels = TRUE) :
  6. #invalid type (list) for variable 'var'

这里可以和我之前的https://www.yuque.com/jingjing-ohrxq/poi2hf/pzax0g[dplyr编程,quote与unquote],进行联动。之前包含tidyverse语法的函数写函数的时候,我们提到需要进行“引用”和“反引用”,同时,这里在LM函数中,也遇到了类似的情况
这里查阅帮助可知,lm函数的第一个参数为formula,

  1. # lm(formula = , data = )

因此,我们可以使用parse函数和eval函数将字符串形式的”wt ~ mpg”转换为formula,再带入lm函数后可以正确运行

  1. lm_func <- function(var) {
  2. lm(eval(parse(text = paste0("wt ~ ", var))), data = mtcars)
  3. }
  4. lm_func('mpg')
  5. #除了使用parse函数和eval函数,另一种方法是使用formula函数将字符串"wt ~ mpg"直接转换为formula
  6. lm_func <- function(var) {
  7. lm(formula(paste0("wt ~ ", var)), data = mtcars)
  8. }
  9. lm_func('mpg')

绘图函数ggplot中

使用mtcars数据集,以wt为因变量,欲分别绘制mpg、cyl、disp、hp、drat与wt的散点图

  1. plot_func <- function(var) {
  2. ggplot(data = mtcars, aes(x = var, y = wt)) +
  3. geom_point() +
  4. labs(x = var, y = "wt") +
  5. theme_bw()
  6. }
  7. plot_func(var = mpg)
  8. plot_func(var = "mpg")
  9. #Don't know how to automatically pick scale for object of type tbl_df/tbl/data.frame.
  10. #Defaulting to continuous.

使用eval(parse())

  1. ggplot(data = mtcars, aes(x = eval(parse(text = "mpg")),
  2. y = eval(parse(text = "wt")))) +
  3. geom_point() +
  4. labs(x = "mpg", y = "wt") +
  5. theme_bw()
  6. plot_func(var = "mpg")

另一种方法:ggplot函数参数中,将aes改为aes_string可以正确处理字符串对象

  1. plot_func <- function(var) {
  2. ggplot(data = mtcars, aes_string(x = var, y = "wt")) +
  3. geom_point() +
  4. labs(x = var, y = "wt") +
  5. theme_bw()
  6. }
  7. plot_func(var = "mpg")

最近又看到了substitute+eval的用法

  1. library(survival)
  2. t.test2 <- function(x,y,data){
  3. x = substitute(x)
  4. y = substitute(y)
  5. t.test(eval(y)~eval(x),data)
  6. }
  7. t.test2(sex,ph.karno,lung)
  8. ## Welch Two Sample t-test
  9. ## data: eval(y) by eval(x)
  10. ## t = -0.17097, df = 191.23, p-value = 0.8644
  11. ## alternative hypothesis: true difference in means between group 1 and group 2 is not equal to 0
  12. ## 95 percent confidence interval:
  13. ## -3.589164 3.016577
  14. ## sample estimates:
  15. ## mean in group 1 mean in group 2
  16. ## 81.82482 82.11111