【问题标题】:Is there a standard way to document data frames?有记录数据框的标准方法吗?
【发布时间】:2012-07-06 02:14:00
【问题描述】:

给定一个数据框 DF,使用save() 将 DF 保存为 R 对象并与同事共享很简单。但是,通常需要附加一个单独的文档来解释精确的列定义。是否有(标准/通用)方法将此信息包含在对象中?

如果我们为 DF 构建了一个包,我们可以创建一个帮助页面来解释所有这些细节,比如内置数据集。因此数据和解释总是可用的,我们只需要共享一个包源文件。但是,对于这个问题,构建一个包似乎过分了。 (作为附带的好处,我们将获得对数据集的版本控制,因为更改会增加包版本号)。

Hmisc 包包含label() 函数,它为对象添加了一个新属性。包含用于子集/创建/等 data.frames 的相关方法以传播新属性(因为属性通常会被大多数函数删除)。

设置属性显然是编写包的替代方法,我们可以添加任意命名的属性。

一个简单的例子:

DF <-
structure(list(Gender = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Female",
"Male"), class = "factor"), Date = structure(c(15518, 15524,
15518, 15526, 15517, 15524), class = "Date"), Dose = c(15, 10,
11, 11, 12, 14), Reaction = c(7.97755180189919, 11.7033586194156,
9.959784869289, 6.0170950790238, 1.92480908119655, 7.70265419443507
)), .Names = c("Gender", "Date", "Dose", "Reaction"), row.names = c(NA,
-6L), class = "data.frame")

library(Hmisc)

label(DF$Reaction) <- "Time to react to eye-dot test, in seconds, recorded electronically"

# or we could set our own attributes

attr(DF$Date,"Description") <- "Date of experiment. Note, results are collected weekly from test centres"

# Since Hmisc adds class "labelled" to data.frame and impelments
# the appropriate methods, the formed is retained on subsetting 
# (not that this is feature is wanted)

DF.mini <- DF[ DF$Gender=="Male",]


# compare
str(DF)      # Not quite sure why str() prints the label attribute but not the Desciptions
str(DF.mini) # we retain the label attribute

attributes(DF$Date)
attributes(DF.mini$Date) # we lose the Description attribute

所以我的问题:

  1. 人们是否在他们的对象中包含额外的信息(我的示例是一个数据框,但适用于所有 R 对象),将所有相关信息保存在一个位置?
  2. 如果是,怎么做?
  3. 很好奇,为什么str() 打印标签属性,我相信 Hmisc 包在某处添加了另一个函数/方法,但不明白为什么 - 有人可以解释一下吗?

【问题讨论】:

  • 将数据与关联的 .Rd 文件一起打包是一种干净的解决方案,并且最接近“标准”方法。或者,使用Hmisc::label()comment()attr(),如对this very similar question 的回复中所述。所以你基本上回答了你自己的问题,除了关于str() ...
  • ... 这可能与Hmisc' print.labelled() 方法有关。
  • 有一些非常好的答案的相关问题:stackoverflow.com/questions/7979609/…
  • 这与记录一个函数有关,但同样的概念也适用:stackoverflow.com/questions/6324568/…

标签: r dataframe


【解决方案1】:

有一个基本函数:comment,它可以分配或检索存储在属性中的文本。

(我不明白为什么str打印标签的问题。str不应该显示所有(非名称,非类,非行名)属性吗?)

【讨论】:

  • 谢谢你的回答,我忘记了comment()函数。我将尝试使用 roxygen 方法,但 comment() 也很方便。当我使用 str() 函数时,加载了 Hmisc 并带有标签属性的对象,它显示标签属性 - 而我的任意描述属性没有打印。我假设 Hmisc 添加了一种方法或更改了某些内容,但看不到什么。 (我是否应该将此作为一个新问题问 - 有点偏离主题)
  • 是的。我认为 Hmisc 版本可能会收集属性,而 comment 似乎只是用于文本。您可以通过以下方式查看代码:require(Hmisc); label.data.frame; label.default
猜你喜欢
  • 2020-09-19
  • 2023-03-05
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 2011-01-08
  • 2015-10-15
相关资源
最近更新 更多