R attributes() attr()


两个函数实际上就是为对象创建属性

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"


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM