在我正在研究的一个软件包中,我遇到了一个看似简单的问题 - 但我无法弄清楚:
子函数有两个参数:
obj
, 一个 data.frame
foo
, 一个 call
例如:
> head(obj)
cadmium copper lead zinc elev
1 11.7 85 299 1022 7.909
2 8.6 81 277 1141 6.983
3 6.5 68 199 640 7.800
4 2.6 81 116 257 7.655
5 2.8 48 117 269 7.480
6 3.0 61 137 281 7.791
> foo
log(cadmium)
> class(foo)
[1] "call"
Run Code Online (Sandbox Code Playgroud)
在那个例子中,我想创建一个向量x <- log(obj$cadmium)
.我怎么做?我尝试使用,with()
但我没有得到预期的结果:
> with(obj, foo)
log(cadmium)
Run Code Online (Sandbox Code Playgroud)
foo
是用户通过在data.frame的列上指定转换而创建的调用obj
:
my_function(obj, foo = log(cadmium)) { ... }
Run Code Online (Sandbox Code Playgroud)
dput()
数据片段:
obj <- structure(list(cadmium = c(11.7, 8.6, 6.5, 2.6, 2.8, 3), copper = c(85L,
81L, 68L, 81L, 48L, 61L), lead = c(299L, 277L, 199L, 116L, 117L,
137L), zinc = c(1022L, 1141L, 640L, 257L, 269L, 281L), elev = c(7.909,
6.983, 7.8, 7.655, 7.48, 7.791)), .Names = c("cadmium", "copper",
"lead", "zinc", "elev"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
Run Code Online (Sandbox Code Playgroud)
Rei*_*son 11
您需要评估呼叫,例如使用eval()
:
foo <- call("log", quote(cadmium))
with(obj, eval(foo))
Run Code Online (Sandbox Code Playgroud)
这使:
> with(obj, eval(foo))
[1] 2.4595888 2.1517622 1.8718022 0.9555114 1.0296194 1.0986123
Run Code Online (Sandbox Code Playgroud)
obj
您显示的数据片段在哪里.
eval()
还有一个envir
参数,指示评估表达式的环境.因此,您可以直接执行您想要的with()
操作eval()
:
> eval(foo, envir = obj)
[1] 2.4595888 2.1517622 1.8718022 0.9555114 1.0296194 1.0986123
Run Code Online (Sandbox Code Playgroud)