r - 向R中的列表项添加描述
问题描述
有没有办法为 R 列表中的项目添加描述?我想将四个数据框组合成一个列表,但除了列表中每个数据框的名称外,我还希望列表包含数据框的简要描述。
例如,我想要一行来做类似下面代码(伪编码)中最后一行的事情。
a <- matrix(rnorm(9), nrow=3, ncol=3)
b <- matrix(rnorm(9), nrow=3, ncol=3)
c <- matrix(rnorm(9), nrow=3, ncol=3)
d <- matrix(rnorm(9), nrow=3, ncol=3)
dat <- list(a, b, c, d)
names(dat) <- c("subject_info", "sample_info", "study_info", "test_info")
# description(dat$subject_info) <- "Subject-by-subject summary of results from the clinical trial"
解决方案
借用@akrun 的评论,这样做的自然方法是使用 R 的help("attributes")
. 另请参阅Hadley Wickham 的 Advanced R。
如果您想自动化获取和设置特殊属性的任务,在本例中为属性"description"
,请定义 getter 和 setter 函数。
description <- function(x){
attr(x, "description")
}
`description<-` <- function(x, value){
attr(x, "description") <- value
x
}
description(dat$subject_info) <- "Subject-by-subject summary of results from the clinical trial"
现在看看它是否有效。
description(dat$subject_info)
#[1] "Subject-by-subject summary of results from the clinical trial"
笔记。
一些具有长名称且多次使用的基本 R 函数具有短名称形式。一个例子是coefficients
和等价的coef
。如果您打算使用这些功能,您可以定义短名称别名。
# aliases
descr <- description
`descr<-` <- `description<-`
descr(dat$sample_info) <- "A test"
descr(dat$sample_info)
#[1] "A test"
lapply(dat, descr)
推荐阅读
- vba - 从 Outlook 中特定联系人(发件人)的电子邮件中提取 pdf 文件时出错
- php - 类型声明解决了奇怪的“未定义索引”错误
- python - 如何在 list_filter django 中添加搜索框?
- google-sheets - 增加文本值的公式
- javascript - 从任何浏览器中唯一识别计算机的挑战
- regex - Regex match hyphenated word with hyphen-less query
- linux - 如何正确设置软硬限制?
- reactjs - 如何在 Material-UI V5 (@mui/lab) datepicker 组件上设置一个空标签?
- java - 这些参数应该是常量还是常规整数?
- c++ - wxWidgets: wxWebView::CanCopy - 防止用户复制需要示例