表达式函数"/>
R语言中的表达式函数
狭义表达式指表达式(expression)类对象,由expression函数产生;而广义的表达式既包含expression类,也包含R“语言”类(language)。expression和language是R语言中两种特殊数据类:
getClass("expression") #expression由向量派生得到getClass("language") #虚拟类(程序控制关键词和name/call子类)
Virtual Class "language" [package "methods"]
No Slots, prototype of class "name"
Known Subclasses:
Class "name", directly
Class "call", directly
Class "{", directly
Class "if", directly
Class "<-", directly
Class "for", directly
Class "while", directly
Class "repeat", directly
Class "(", directly
Class ".name", by class "name", distance 2, with explicit coerce
1.expression
expression(..)
#产生未评估求值(evaluate)的表达式(expression类型的向量/列表,[,[[,$进行子集化), ..-R对象(通常是call类型,符号或常量),返回值的长度等于参数个数
is.expression(x)
as.expression(x,..) #x任意R对象
######################
length(ex1<-expression(1 + 0:9)) # 1
eval(ex1) # 1:10length(ex2<-expression(u, v, 1+ 0:9)) # 3
ex3<-expression(u, v, z=1+0:9)
#子集化
mode(ex3 [3]) # expression
mode(ex3[[3]]) # call
mode(ex3$z) # call
typeof(ex3$z) # language
mode(ex3[[2]]) # name
typeof(ex3[[2]]) #symbol
ex3$z<-NULL # 删除#注:expression函数将参数当做列表处理,故参数要符合列表元素的书写规则
2.parse
一般用于从文件中读取文本作为表达式,返回expression类
parse(file = "", n = NULL, text = NULL, prompt = "?", keep.source = getOption("keep.source"), srcfile, encoding = "unknown")cat("x<-c(1,4)\n x^3-10; outer(1:7,5:9)\n", file="xyz.Rdmped")
parse(file="xyz.Rdmped", n=2) #expression(x<-c(1,4)\n x^3-10)
unlink("xyz.Rdmped")parse(text="a+b")
expression(a+b)
3.quote
quote(expr) #expr-任何语法上有效的R表达式,返回值一般情况下是call类,expr是单个变量时为name类,expr为常量时返回值的存储模式与相应常量的存储模式相同
cl<-quote(1 + sqrt(a) + b^c) #1 + sqrt(a) + b^c
mode(cl) #"call"
typeof(cl) #"language"
cl <- quote(a)
mode(cl) #"name"
length(cl) # 1
typeof(cl) #"symbol"
cl<-quote(1)
mode(cl) #"numeric"
typeof(cl) #"double"
4.substitute
若不使用环境变量或环境变量参数,substitute函数得到的结果与quote函数相同
substitute(expr,env) #expr-任何语法上有效的R表达式,env-环境或列表对象,默认为当前环境
substitute(1 + sqrt(a) + b^c) == quote(1 + sqrt(a) + b^c) #TRUE
ss <- substitute(y == sqrt(a, b), list(a = 3, b = 2))a=1
substitute(a+b,list(a=a)) #1+b
5.deparse
将未评估的表达式转换成字符串
deparse(expr, width.cutoff = 60L, backtick = mode(expr) %in% c("call", "expression", "(", "function"), control = c("keepInteger", "showAttributes", "keepNA"), nlines = -1L)
#expr-any r expression,"call"/"expression"/"function"/"("
#backtick-逻辑值,当不遵循标准语法时-符号名称是否应该用反引号括起来
#width.cutoff-[20,500]中的整数,确定尝试换行的截止(以字节为单位)
#control="all"最接近deparse()为parse()的反转deparse(args(lm))
deparse(args(lm), width = 500)e<-quote(`foo bar`) #name类
deparse(e) #"foo bar"
deparse(e, backtick = TRUE) #"foo bar"e <- quote(`foo bar`+1)
deparse(e,backtick=FALSE)
deparse(e,backtick=TRUE)
deparse(e,control = "all") #"quote(`foo bar` + 1)"
deparse(e,backtick=FALSE,control = "all")
更多推荐
R语言中的表达式函数
发布评论