【问题标题】:Setting a value to a dynamically executed function in R在 R 中为动态执行的函数设置一个值
【发布时间】:2020-04-30 01:55:29
【问题描述】:

对于实验室数据,测量值通常带有检测/报告限值和置信区间。例如,我可能测量了水中的镁浓度,其中最小报告值为 5,我收到了两次测量,第一次是 10,第二次是“

我解决这个问题的方法是构造一个带有属性 LRL(报告下限)的 S3 类。我希望能够让用户执行以下操作:

a <- set_measurement("<5", LRL = 5)
b <- set_measurement(8, LRL = 5)
set_conservatism(1) # sets a global variable called "conservatism_coefficient" to 1
a
# 5 [LRL: 5]
c <- b + a
# 13 [LRL: 5]
set_conservatism(0.5)
a
# 2.5 [LRL: 5]
b + a
# 10.5 [LRL: 5]
c
# 13 [LRL: 5]

我想象的是“a”的值以某种方式设置为“LRL*conservatism_co-efficient”而不是一个数字。然后当其他一些函数尝试访问该值时,该值是基于动态计算的当前的 conservatism_co-efficient。

这可能吗,和/或我只是以完全错误的方式解决这个问题?

【问题讨论】:

  • 首先,这是一个非常有趣的想法。如果它不存在,我希望你继续沿着这条路走下去。听起来您在谈论物理化学,但这也可以应用于医学。其次,我认为这是可行的。不幸的是,我认为这将需要为许多不同的功能制定方法。查看this section of Advanced R 了解您正在处理的内容。
  • @IanCampbell 这正是我试图避免做的事情。我希望可能有某种方法可以在将值传递给其他函数之前计算它,而不是需要重新编写基本上每个通用函数。哦,好吧,也许这就是为什么其他人似乎还没有这样做的原因。

标签: r class attributes chemistry dynamic-function


【解决方案1】:

不要害怕尝试重载您需要的泛型函数。您只需修改 print 函数和算术运算组 Ops 即可实现您想要的:

set_conservatism = function(factor) {
    # Set global CONSERVATISM
    CONSERVATISM <<- factor
}

set_measurement = function(value, lrl=5) {
    # Create a new measurement
    v_ = "measurement"  # Dummy identifier

    # Set attributes of a measurement
    measurement = structure(v_, "value"=value, "lrl"=lrl)
    # Set class attribute of measurement
    class(measurement) = "measurement"
    measurement
}

update_measurement = function(x) {
    # Return value of measurement based on CONSERVATISM
    if (attr(x, "value") < attr(x, "lrl")) {
        attr(x, "lrl") * CONSERVATISM
    } else {
        attr(x, "value")
    }
}

print.measurement = function(x, ...) {
    # UserMethod for printing a measurement
    update_measurement(x)
}

Ops.measurement = function(e1, e2) {
    # UserMethod for arithmetic operations with measurements
    e1 = update_measurement(e1)
    e2 = update_measurement(e2)
    NextMethod(.Generic)
}

a = set_measurement(0)  # Any value smaller than lrl will do
b = set_measurement(8)

set_conservatism(1)

a + b
>>> 13

set_conservatism(0.5)

a + b
>>> 10.5

(来自 Python 程序员的附注:使用 Python 中的 properties 和重写魔术方法很容易实现这样的事情)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    相关资源
    最近更新 更多