最近我在我的R代码中遇到了以下问题。在接受数据框作为参数的函数中,我需要添加(或替换,如果存在)一列,其中包含根据数据框原始列的值计算的数据。我编写了代码,但测试显示数据框提取/替换操作,我用过,结果是对象的特殊(用户定义)属性丢失.
在意识到这一点并通过阅读 R 文档确认该行为之后(http://stat.ethz.ch/R-manual/R-patched/library/base/html/Extract.html http://stat.ethz.ch/R-manual/R-patched/library/base/html/Extract.html),我决定非常简单地解决这个问题 - 通过saving提取/替换操作之前的属性和恢复此后他们:
myTransformationFunction <- function (data) {
# save object's attributes
attrs <- attributes(data)
<data frame transformations; involves extract/replace operations on `data`>
# restore the attributes
attributes(data) <- attrs
return (data)
}
这种方法奏效了。然而,无意中,我看到了另一篇 R 文档(http://stat.ethz.ch/R-manual/R-patched/library/base/html/Extract.data.frame.html http://stat.ethz.ch/R-manual/R-patched/library/base/html/Extract.data.frame.html),恕我直言,它提供了一个有趣的(并且可能是一个更通用的?)替代方法解决同样的问题:
## keeping special attributes: use a class with a
## "as.data.frame" and "[" method:
as.data.frame.avector <- as.data.frame.vector
`[.avector` <- function(x,i,...) {
r <- NextMethod("[")
mostattributes(r) <- attributes(x)
r
}
d <- data.frame(i = 0:7, f = gl(2,4),
u = structure(11:18, unit = "kg", class = "avector"))
str(d[2:4, -1]) # 'u' keeps its "unit"
如果这里的人们可以通过以下方式提供帮助,我将非常感激:
比较上述两种方法,如果它们具有可比性(我意识到定义的第二种方法是针对数据帧的,但我怀疑它可以推广到任何对象);
解释第二种方法中函数定义的语法和含义,特别是as.data.frame.avector
,以及这条线的目的是什么as.data.frame.avector <- as.data.frame.vector
.