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