S3 オブジェクトの構築に関する Hadley のアドバイスを読んで、私はヘルパー関数、コンストラクター関数、およびバリデーター関数を使用しています。簡単な再現可能な例:
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
}
結果のオブジェクトに、渡されたアイテムが持っていた元の名前の値を含めたいと思います ($x_name
上記の例)。コンストラクターを直接呼び出すと、deparse(substitute(...))
トリックが機能します。
alpha = "a"
test_constructor <- new_test_object(x = alpha, y = "b", z = "c")
test_constructor$x_name
# [1] "alpha"
しかし、ヘルパー関数を使用する場合はそうではありません:
test_helper <- test_object(x = alpha, y = "b", z = "c")
test_helper$x_name
# [1] "x"
私test_helper$x_name
も戻りたい[1] "alpha"
です。
deparse(substitute(...))
ヘルパー段階でステップを実行する以外に、コンストラクター関数 ( )がヘルパー経由でnew_test_object()
オブジェクトの「元の」名前にアクセスする方法はありますか? x
または、ヘルパー関数がそれをコンストラクターに渡すときに、その名前が確実に通過するようにしますか?