[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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 空气有了记忆 长在南方的街头 唤醒了北方的萧瑟 只是多捏了一把水珠 枯槁叶子在枝头晃动 风结束了他的挣扎 它消逝还...
    Sophie朵儿阅读 2,224评论 0 0
  • 宝贝,你好! 暑假一转眼四分之一过去了,不知道你有什么收获?进入一年之中最热的三伏天了,外面的空气都是热的,让人喘...
    安妮虾阅读 2,481评论 0 0
  • 库伯先生是个典型的德国人,目测大约有1米9几,棱角分明的脸庞上,突兀地安置了一个大大的鼻子。身材匀称,骨节粗大,能...
    827943a9c996阅读 3,418评论 0 0
  • 中午外婆和小姨来我们家吃饭,围坐在桌旁时,大家都在继承着中华民族的优良传统---边吃边聊。小姨是刚从汕头回来,很久...
    许久0929阅读 1,534评论 0 0
  • 前言 今天评测的这款来自谷得游戏的「世界2-暴风帝国」,这款从去年就推出预热单机「世界2-魔物狩猎」的游戏,玩过单...
    onlinew阅读 4,560评论 0 1