首页 > 解决方案 > 向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"

标签: rlist

解决方案


借用@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)

推荐阅读