兩個函數實際上就是為對象創建屬性
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"