Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R对象';s名称承载多个功能_R_Nse_R S3 - Fatal编程技术网

R对象';s名称承载多个功能

R对象';s名称承载多个功能,r,nse,r-s3,R,Nse,R S3,根据我的阅读,我使用了一个助手函数、一个构造函数和一个验证器函数。一个简单的可复制示例: test_object <- function(x, y, z) { new_test_object(x, y, z) } new_test_object <- function(x, y, z) { structure(list(x = x, y = y, z = z,

根据我的阅读,我使用了一个助手函数、一个构造函数和一个验证器函数。一个简单的可复制示例:

test_object <- function(x, y, z) {
    new_test_object(x, y, z)
}

new_test_object <- function(x, y, z) {
    structure(list(x = x,
                   y = y,
                   z = z,
                   x_name = deparse(substitute(x))),
              class = "test_object")
}

validate_test_object <- function(test_object) {
    # Anything goes
    test_object
}
但如果我使用helper函数,则不会:

test_helper <- test_object(x = alpha, y = "b", z = "c")
test_helper$x_name
# [1] "x"

test\u helper这里有一个不完美的解决方案:当您从另一个函数调用名称时,添加
..
参数来传递名称

test_object <- function(x, y, z) {
  x_name = deparse(substitute(x))
  new_test_object(x, y, z, x_name = x_name)
}

new_test_object <- function(x, y, z, ...) {
  args <- list(...)
  if(is.null(args[["x_name"]])){
    structure(list(x = x,
                   y = y,
                   z = z,
                   x_name = deparse(substitute(x))),
              class = "test_object")
  }
  else{
    structure(list(x = x,
                   y = y,
                   z = z,
                   x_name = args[["x_name"]]),
              class = "test_object")
  }

}

test\u object这里的真正目的是什么?如果您只是使用一个函数作为另一个函数的包装器,那么有更好的方法来保存参数。比如说

test_object <- function(x, y, z) {
  call <- match.call()
  call[[1]]  <- quote(new_test_object)
  eval(call)
}
诚实地回答“这里的真正目的是什么?”:因为哈德利是这么说的!他的逻辑是helper“为其他人构造和验证(创建)这个类的对象提供了一种方便且灵活的参数化方法。”。我喜欢你的建议或适当地参数化它-看起来很整洁,好像它会做得很好。谢谢
test_helper <- test_object(x = alpha, y = "b", z = "c")
test_helper$x_name
# [1] "alpha"
test_object <- function(x, y, z) {
  call <- match.call()
  call[[1]]  <- quote(new_test_object)
  eval(call)
}
test_object <- function(x, y, z, xname=deparse(substitute(x))) {
    new_test_object(x, y, z, xname=xname)
}

new_test_object <- function(x, y, z, xname=deparse(substitute(x))) {
    structure(list(x = x,
                   y = y,
                   z = z,
                   x_name = xname),
              class = "test_object")
}