[R]-Attributes

y <- 1:10

# set attributes
attr(y, "my_attr") <- "This is a vector"

# get attributes
attr(y, "my_attr")
#> [1] "This is a vector"

# get all attributes as a list
attributes(y)
#> $my_attr
#> [1] "This is a vector"

str(attributes(y))
#> List of 1
#>  $ my_attribute: chr "This is a vector"

The structure() function returns a new object with modified attributes:

structure(1:10, my_attr = "This is a vector")
#>  [1]  1  2  3  4  5  6  7  8  9 10
#> attr(,"my_attribute")
#> [1] "This is a vector"

The only attributes not lost are the 3 most important:

  • Names, a character vector giving each element a name, described in names.
  • Dimensions, used to turn vectors into matrices and arrays, described in matrices and arrays.
  • Class, used to implement the S3 object system, described in S3.

Each of these attributes has a specific accessor function to get and set values. When working with these attributes, use names(x), dim(x), and class(x), not attr(x, "names"), attr(x, "dim"), and attr(x, "class").

names

You can name a vector in three ways: \index{attributes|names}

  • When creating it: x <- c(a = 1, b = 2, c = 3).
  • By modifying an existing vector in place: x <- 1:3; names(x) <- c("a", "b", "c").
  • By creating a modified copy of a vector:
x <- 1:3
setNames(x, c("a", "b", "c") )
# this is just a short form of
names(x) <-  c("a", "b", "c")

Names don't have to be unique. However, character subsetting, described in subsetting, is the most important reason to use names and it is most useful when the names are unique.

Not all elements of a vector need to have a name. If some names are missing, names() will return an empty string for those elements. If all names are missing, names() will return NULL.

y <- c(a = 1, 2, 3)
names(y)

z <- c(1, 2, 3)
names(z)

You can create a new vector without names using unname(x), or remove names in place with names(x) <- NULL.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 空氣有了記憶 長(zhǎng)在南方的街頭 喚醒了北方的蕭瑟 只是多捏了一把水珠 枯槁葉子在枝頭晃動(dòng) 風(fēng)結(jié)束了他的掙扎 它消逝還...
    Sophie朵兒閱讀 325評(píng)論 0 0
  • 寶貝,你好! 暑假一轉(zhuǎn)眼四分之一過(guò)去了,不知道你有什么收獲?進(jìn)入一年之中最熱的三伏天了,外面的空氣都是熱的,讓人喘...
    安妮蝦閱讀 351評(píng)論 0 0
  • 庫(kù)伯先生是個(gè)典型的德國(guó)人,目測(cè)大約有1米9幾,棱角分明的臉龐上,突兀地安置了一個(gè)大大的鼻子。身材勻稱,骨節(jié)粗大,能...
    827943a9c996閱讀 552評(píng)論 0 0
  • 中午外婆和小姨來(lái)我們家吃飯,圍坐在桌旁時(shí),大家都在繼承著中華民族的優(yōu)良傳統(tǒng)---邊吃邊聊。小姨是剛從汕頭回來(lái),很久...
    許久0929閱讀 244評(píng)論 0 0
  • 前言 今天評(píng)測(cè)的這款來(lái)自谷得游戲的「世界2-暴風(fēng)帝國(guó)」,這款從去年就推出預(yù)熱單機(jī)「世界2-魔物狩獵」的游戲,玩過(guò)單...
    onlinew閱讀 1,143評(píng)論 0 1

友情鏈接更多精彩內(nèi)容