如果我有一个带参数的函数x,并假设函数期望x是一个向量,我该如何测试x是一个向量还是一个指向向量的东西?
fun <- function(x) {
brilliant manipulation of x here
output based on manipulation of x here
}
Run Code Online (Sandbox Code Playgroud)
例如,我如何区分案例1:
myvector <- c(1,2,3)
fun(myvector)
Run Code Online (Sandbox Code Playgroud)
案例2:
fun(c(1,2,3))
Run Code Online (Sandbox Code Playgroud)
我希望fun()能够"Output concerning myvector"为案例1 输出.
我希望fun()能够"Output concerning x"为案例2 输出.
我很失落之中substitute,deparse和各种杂相关的想法.照明赞赏.
怎么样
fun<-function(x) {
pp<-substitute(x)
nn<- if(is.name(pp)) {
deparse(pp)
} else {
"x"
}
paste("Output concerning", nn)
}
myvector <- c(1,2,3)
fun(c(1,2,3))
# [1] "Output concerning x"
fun(myvector)
# [1] "Output concerning myvector"
Run Code Online (Sandbox Code Playgroud)
我们substitute用来看看传递的内容.如果是a name,则假设它是变量名称并且deparse()获取名称的字符版本,否则使用"x".
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |