狹義表達式指表達式(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:10
length(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")