gpt4 book ai didi

r - 是否有记录数据框的标准方法?

转载 作者:行者123 更新时间:2023-12-04 02:19:25 24 4
gpt4 key购买 nike

给定一个数据框 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 包在某处添加了另一个函数/方法,但不明白为什么 - 有人可以解释一下吗?
  • 最佳答案

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

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

    关于r - 是否有记录数据框的标准方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11348320/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com