已将 match.call 解析为命名列表
deparsed match.call to a named list
我在我的一个函数中对调用进行了解析(以使其更易于阅读),并将其作为输出 S3 对象的一部分包含在内,以供最终用户参考。
func1 <- function(v1, v2, ...){
return(deparse(match.call()))
}
obj <- func1(11, 22, v3 = 33)
obj
变量现在包含:
"func1(v1 = 11, v2 = 22, v3 = 33)"
现在在接受此对象作为输入的另一个函数中,我想将此调用字符向量转换为命名列表,使其具有与以下结构相同的结构:
list(v1 = 11, v2 = 22, v3 = 33)
$v1
[1] 11
$v2
[1] 22
$v3
[1] 33
需要说明的是,我不愿意按原样存储调用对象,因为在用户探索 S3 对象时,它不会为用户提供应有的信息(我认为程序员应该处理所有事情,并且用户应该只是喜欢这个功能)。
这个怎么样
to_list <- function(x) {
xex <- parse(text= x )[[1]]
xex[[1]] <- quote(list)
eval.parent(xex)
}
to_list(obj)
基本上我们将字符串解析回一个表达式,然后用 list()
函数换出原来的函数名可以计算它以实际构建列表。
考虑到 obj
是您在问题中显示的字符串,您可以执行以下操作:
eval(parse(text=sub("^.+?\(","list(",obj)))
但是如果你想把它放在函数里面,你可以做下面的事情来避免反解析和解析:
func1 <- function(v1, v2, ...){
# catch the call
tmp_the_call <- match.call()
# convert to list
tmp_the_call <- as.list(tmp_the_call)
# remove the function name
tmp_the_call <- tmp_the_call[-1]
return(tmp_the_call)
}
# Or as one-liner
func1 <- function(v1, v2, ...){
return(as.list(match.call())[-1])
}
func1("qq", "ww", v3 = "ee", "rr")
这将导致:
$v1
[1] "qq"
$v2
[1] "ww"
$v3
[1] "ee"
[[4]]
[1] "rr"
我在我的一个函数中对调用进行了解析(以使其更易于阅读),并将其作为输出 S3 对象的一部分包含在内,以供最终用户参考。
func1 <- function(v1, v2, ...){
return(deparse(match.call()))
}
obj <- func1(11, 22, v3 = 33)
obj
变量现在包含:
"func1(v1 = 11, v2 = 22, v3 = 33)"
现在在接受此对象作为输入的另一个函数中,我想将此调用字符向量转换为命名列表,使其具有与以下结构相同的结构:
list(v1 = 11, v2 = 22, v3 = 33)
$v1
[1] 11
$v2
[1] 22
$v3
[1] 33
需要说明的是,我不愿意按原样存储调用对象,因为在用户探索 S3 对象时,它不会为用户提供应有的信息(我认为程序员应该处理所有事情,并且用户应该只是喜欢这个功能)。
这个怎么样
to_list <- function(x) {
xex <- parse(text= x )[[1]]
xex[[1]] <- quote(list)
eval.parent(xex)
}
to_list(obj)
基本上我们将字符串解析回一个表达式,然后用 list()
函数换出原来的函数名可以计算它以实际构建列表。
考虑到 obj
是您在问题中显示的字符串,您可以执行以下操作:
eval(parse(text=sub("^.+?\(","list(",obj)))
但是如果你想把它放在函数里面,你可以做下面的事情来避免反解析和解析:
func1 <- function(v1, v2, ...){
# catch the call
tmp_the_call <- match.call()
# convert to list
tmp_the_call <- as.list(tmp_the_call)
# remove the function name
tmp_the_call <- tmp_the_call[-1]
return(tmp_the_call)
}
# Or as one-liner
func1 <- function(v1, v2, ...){
return(as.list(match.call())[-1])
}
func1("qq", "ww", v3 = "ee", "rr")
这将导致:
$v1 [1] "qq" $v2 [1] "ww" $v3 [1] "ee" [[4]] [1] "rr"