7

最近我在我的 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"

如果这里的人们可以通过以下方式提供帮助,我将不胜感激:

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

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

4

1 回答 1

2

我正在回答我自己的问题,因为我刚刚发现了一个 SO 问题(如何在不丢失属性的情况下从 data.frame 中删除一行),其答案涵盖了我上面提出的大部分问题。但是,对于第二种方法的其他解释(对于 R 初学者)仍然值得赞赏。

更新:

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

于 2014-05-24T05:00:27.350 回答