是否有更简单的方法来访问R中的类的属性,我可以使用点表示法吗?

时间:2011-06-23 05:05:44

标签: r object attributes

我在R中创建了一个包含多个属性的对象。我怎样才能轻松访问它们?

我能做到:

attr(x, attributeName)

或:

attributes(x)$attributeName

但它们都不是很方便。

有更快的方法(比如C ++或Java中的点)吗?

4 个答案:

答案 0 :(得分:16)

attributes()返回一个命名列表。我打电话给它并存储它们,然后通过名字访问。如果您不需要,可以反复调用attr()attributes()

x <- 1:10
attr(x, "foo") <- "a"
attr(x, "bar") <- "b"
(features <- attributes(x))

给出:

R> (features <- attributes(x))
$foo
[1] "a"

$bar
[1] "b"

然后以通常的方式访问

R> features["foo"]
$foo
[1] "a"

R> features$foo
[1] "a"

答案 1 :(得分:12)

不要使用对象的属性,请使用列表:

myobj <- structure(list(a = 1, b = 2), class = "myclass")
print.myclass <- function(x, ...) cat("A: ", x$a, " B: ", x$b, "\n", sep = "")
myobj

当然,如果您扩展现有对象(例如矢量),这可能不起作用,但根据我的经验,这通常是构建对象的更好方法。

答案 2 :(得分:9)

可能没有与内部功能相对应的内置功能。在C ++中,你可以这样定义:

> `%.%` <- function(o, a) attr(o, as.character(substitute(a)))
> x <- 1
> attr(x, "orz") <- 2
> x%.%orz
[1] 2

答案 3 :(得分:2)

使用从regexpr返回的match.length属性的示例:

向量中的三个字符串,第一个和第三个字符串包含嵌入字符串:

data=c("<a href=\"ch4.html\">Chapter 1</a>",
       "no quoted string is embedded in this string",
       "<a   href=\"appendix.html\">Appendix</a>")

使用regexpr找到嵌入的字符串:

> locations <- regexpr("\"(.*?)\"", data)

匹配在第一个字符串中(在9处长度为10)和第三个字符串(在11处长度为15):

> locations
[1]  9 -1 11
attr(,"match.length")
[1] 10 -1 15
attr(,"useBytes")
[1] TRUE

来自属性的矢量:

> attr(locations,"match.length")
[1] 10 -1 15

使用substr和属性向量来提取字符串:

> quoted_strings=substr( data, 
                         locations, 
                         locations+attr(locations,"match.length")-1 )    
> quoted_strings
[1] "\"ch4.html\""      ""                  "\"appendix.html\""

也许您想从字符串中删除嵌入的引号字符:

> gsub("\"", "", quoted_strings)
[1] "ch4.html"      ""              "appendix.html"

另一种方法是使用regmatches:

> regmatches(data,locations)
[1] "\"ch4.html\""      "\"appendix.html\""