R-parse() function and eval() function

Table of contents

1-parse() function

2-eval() function

3- Example

3-1 Converting a String Object to a Number

3-2 Using the eval() function to evaluate the value of an expression

3-3 In the regression function lm


1-parse() function

parse: parse

Convert a character class object to an expression class object .

Usage: parse(text = character)

> x <- "sin(pi/2)"
> class(x)
[1] "character"



> x1 <- parse(text = x)
> class(x1)
[1] "expression"

2-eval() function

eval: evaluate

The type of the object to be evaluated can be a call-like object, an expression-like object or a name (looks up a name in the current scope and evaluates its binding), a promise, or any primitive type such as a vector, function, and environment (returns with constant).

Convert an expression class object to a numeric value .

Usage: eval(expr) where expr represents the object to be evaluated

> x <- "2 ^ 3"
> eval(x)
[1] "2 ^ 3"
> x1 <- parse(text=x)
> eval(x1)
[1] 8

3- Example

3-1 Converting a String Object to a Number

#b是个字符串对象,使用双引号将内容括起来。
> b <- "
+ for (i in 1:5) {
+   print(i)
+ }
+ "

> class(b)
[1] "character"


#使用parse()函数将字符对象转换为表达式对象
> parsed_b <- parse(text = b)
> parsed_b
expression(for (i in 1:5) {
  print(i)
})
> class(parsed_b)
[1] "expression"


#使用eval()函数评估表达式对象的值
> eval(parsed_b)
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

3-2 Using the eval() function to evaluate the value of an expression

> class(mtcars)
[1] "data.frame"
> class(parse(text = "mtcars"))
[1] "expression"
> class(eval(parse(text = "mtcars")))
[1] "data.frame"
> head(eval(parse(text = "mtcars")))
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

3-3 In the regression function lm

Using the mtcars data set, set wt as the dependent variable, and want to establish regression models for mpg, cyl, disp, hp, drat and wt respectively.

Taking the regression model of wt and mpg as an example, the code is as follows:

> lm(wt ~ mpg, data = mtcars)

Call:
lm(formula = wt ~ mpg, data = mtcars)

Coefficients:
(Intercept)          mpg  
     6.0473      -0.1409  

If the modeling process has many statements, and the different models only change the independent variables, then writing functions can simplify the process.

However, the first problem encountered is, how to specify the arguments when writing the function?

Usually it is easy to think of the following code, but the following code does not work.

data(mtcars)

lm_func <- function(var) {
  lm(wt ~ var, data = mtcars)
}
lm_func(var = "mpg")
lm_fun(var = mpg)

# 正确方式是mtcars[,"mpg"]
lm_func(var = mtcars[,"mpg"])
lm(wt ~ mpg, data = mtcars)

Use the parse function and the eval function to convert the string form "wt ~ mpg" into a formula, and then bring it into the lm function to run correctly

> class(eval(parse(text = "wt ~ mpg")))
[1] "formula"
> lm(eval(parse(text = "wt ~ mpg")), data = mtcars)

Call:
lm(formula = eval(parse(text = "wt ~ mpg")), data = mtcars)

Coefficients:
(Intercept)          mpg  
     6.0473      -0.1409  

It is worth noting that the first parameter of the lm() function is formula. Therefore, based on the above information, the lm_func function can be written as:

> lm_func <- function(var) {
+   lm(eval(parse(text = paste0("wt ~ ", var))), data = mtcars)
+ }
> 
> lm_func(var = "mpg") # 正确执行了

Call:
lm(formula = eval(parse(text = paste0("wt ~ ", var))), data = mtcars)

Coefficients:
(Intercept)          mpg  
     6.0473      -0.1409  

Source: R: parse function and eval function parse strings into commands and run_r language eval(parse_zhihao-pku's blog-CSDN blog

Guess you like

Origin blog.csdn.net/u011375991/article/details/132595618
Recommended