在提取/替换操作期间保留对象属性的方法

Ale*_*ekh 5 attributes r extract object user-defined

最近我在我的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)
}
Run Code Online (Sandbox Code Playgroud)

这种方法奏效了.然而,偶然地,我遇到了另一条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"
Run Code Online (Sandbox Code Playgroud)

如果这里的人能帮助我,我将非常感激:

  1. 比较上述两种方法,如果它们具有可比性(我意识到定义的第二种方法是针对数据帧,但我怀疑它可以推广到任何对象);

  2. 在第二种方法中解释函数定义中的语法和含义,尤其as.data.frame.avector是该行的目的是什么as.data.frame.avector <- as.data.frame.vector.

Ale*_*ekh 2

我正在回答我自己的问题,因为我刚刚发现了一个 SO 问题(How to delete a row from a data.frame而不丢失属性),其答案涵盖了我上面提出的大部分问题。然而,第二种方法的附加解释(对于 R 初学者仍然值得赞赏。

更新:

在对以下SO问题的回答中提出了该问题的另一种解决方案:索引操作删除属性。然而,就我个人而言,我更喜欢这种基于创建新类的方法,因为恕我直言,它在语义上更清晰。