最近我在我的 R 代码中遇到了以下问题。在一个函数中,接受一个数据框作为参数,我需要添加(或替换,如果它存在)一个列,其中包含基于数据框原始列的值计算的数据。我编写了代码,但测试显示我使用的数据框提取/替换操作导致对象的特殊(用户定义)属性丢失。
在通过阅读 R 文档( http://stat.ethz.ch/R-manual/R-patched/library/base/html/Extract.html )意识到这一点并确认该行为后,我决定非常简单地解决问题 -通过在提取/替换操作之前保存属性并在之后恢复它们:
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),它为恕我直言有趣的(并且可能是更通用的?)解决同一问题的替代方法:
## 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
。