【发布时间】: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
所以我的问题:
- 人们是否在他们的对象中包含额外的信息(我的示例是一个数据框,但适用于所有 R 对象),将所有相关信息保存在一个位置?
- 如果是,怎么做?
- 很好奇,为什么
str()打印标签属性,我相信 Hmisc 包在某处添加了另一个函数/方法,但不明白为什么 - 有人可以解释一下吗?
【问题讨论】:
-
将数据与关联的 .Rd 文件一起打包是一种干净的解决方案,并且最接近“标准”方法。或者,使用
Hmisc::label()、comment()或attr(),如对this very similar question 的回复中所述。所以你基本上回答了你自己的问题,除了关于str()... -
... 这可能与
Hmisc'print.labelled()方法有关。 -
有一些非常好的答案的相关问题:stackoverflow.com/questions/7979609/…
-
这与记录一个函数有关,但同样的概念也适用:stackoverflow.com/questions/6324568/…