两个函数实际上就是为对象创建属性
attributes()
读取对象属性
x<- table(c(3,4,6,8,6))
attributes(x)
$dim
[1] 4
$dimnames
$dimnames[[1]]
[1] "3" "4" "6" "8"
$class
[1] "table"
attributes()函数修改属性
如
attributes(x) <- NULL
x
## [1] 1 1 2 1
如上修改后x不再是数组,也不是table
attr函数
可以用attr(x, "属性名")的格式读取或定义x的属性。 如:
x <- c(1,3,5)
attr(x, "theta") <- c(0, 1)
print(x)
## [1] 1 3 5
## attr(,"theta")
## [1] 0 1
可以让向量x额外地保存一个theta属性, 这样的属性常常成为“元数据”(meta data), 比如, 用来保存数据的说明、模拟数据的真实模型参数,等等
对比
x<-c(apple=2.5,orange=2.1)
attributes(x)
$names
[1] "apple" "orange"
attr(x,"names")
[1] "apple" "orange"
attr(x,"names")<-c("apple","grape")
attr(x,"type")<-"fruit"
x
apple grape
2.5 2.1
attr(,"type")
[1] "fruit"
attributes(x)
$names
[1] "apple" "grape"
$type
[1] "fruit"