web-dev-qa-db-ja.com

Rでクラスの属性にアクセスする簡単な方法はありますか?ドット表記を使用できますか?

いくつかの属性を含むオブジェクトをRで作成しました。どうすれば簡単にアクセスできますか?

できます:

attr(x, attributeName)

または:

attributes(x)$attributeName

しかし、どれも本当に便利ではありません。

より速い方法はありますか(C++またはJavaのドットのように)?

27
RockScience

オブジェクトには属性を使用せず、リストを使用します。

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

もちろん、これは既存のオブジェクト(ベクターなど)を拡張する場合は機能しない可能性がありますが、私の経験では、オブジェクトを構築するための一般的に優れた方法です。

12
hadley

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"
17
Gavin Simpson

おそらく、に対応する組み込み関数はありません。 C++では、次のように定義できます。

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

Regexprから返されるmatch.length属性の使用例:

ベクトルの3つの文字列には、最初と3番目に埋め込み文字列が含まれています。

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)

一致は、最初の文字列(長さが10の9)と3番目の文字列(長さが15の11)にあります。

> 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\""
2
Jeff Taylor