给定数据框DF,将DF作为R对象保存save()
并与同事共享是很简单的.但是,通常需要附加一份单独的文档来解释精确的列定义.是否有(标准/通用)方法将此信息包含在对象中?
如果我们为DF构建了一个包,我们可以创建一个帮助页面来解释所有这些细节,比如内置数据集.因此,数据和解释始终可用,我们只需共享一个包源文件.但是,构建一个包似乎过度杀死了这个问题.(作为附带好处,我们将获得对数据集的版本控制,因为更改将增加包版本号).
Hmisc包中包含该label()
函数,该函数向对象添加新属性.包括用于子集化/创建/ etc 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
Run Code Online (Sandbox Code Playgroud)
所以我的问题:
str()
打印label属性,我相信Hmisc包已经在某处添加了另一个函数/方法,但是看不清楚原因 - 有人能解释一下吗? 归档时间: |
|
查看次数: |
322 次 |
最近记录: |