R統計ノート(4)括弧と二重括弧の違い



R Statistical Notes Difference Between Brackets



理解の違いは言語から始まります。 JAVA、C、Javascriptなどの他の言語で慣性的な考え方をしている場合、R言語の括弧の理解は単純に信じられないほどです。

1.すべてのオブジェクトは角括弧を参照できます

はい、間違いではありません。R言語のすべてのオブジェクトは、次のように、スカラー(定数)を含む角かっこを参照できます。



# The first element of scalar always points to itself# The following expression is always true1[1] == 1# Since the above equation is true, then the following equation is also established.1[1][1] == 11[1][1] == 1[1]

オブジェクト指向の考え方によれば、1 [1] [1] == 1 [1]はよく理解されているので、[[1]]をどのように理解しますか? []の分解ですか?

2。[[]]は実際にはメソッドです

データのテストとレビューを繰り返した後、[[]]を組み合わせて、次のようにメソッドまたはアトミック演算子を表すことを理解する必要があります。



# Get the operator [[help?`[[`

あなたが得る助けは次の通りです:

Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does. x$name is equivalent to x[['name', exact = FALSE]]. Also, the partial matching behavior of [[ can be controlled using the exact argument. getElement(x, name) is a version of x[[name, exact = TRUE]] which for formally classed (S4) objects returns slot(x, name), hence providing access to even more general list-like objects.

以下の簡単な翻訳では、[[]]は単一の要素を選択するためのリストである$に似ていますが、唯一の違いは[[次のように、パラメーター 'exact'によってあいまい一致をアクティブにすることです。

# Define list objectli <- list(name='yiifaa', age=35)# Extract elements from the list must use [[]]# Fuzzy match to nameli[['nam', exact=FALSE]]

驚くべきことに、[[]]はあいまいマッチングもサポートしています。
最初のルールと組み合わせると、次の結論を導き出すこともできます。



# If the R language support object is compared, then li[1] == lili[1][[1]] == li[[1]]# Continue to play with themli[[1]][1] == li[[1]]

さて、たくさんの例を読んでから、次の式を理解する方法を読んでください。

li[[[1]]]

もちろん、[[[[]のようなものはないので、それは間違っています。

結論として

R言語では、[]と[[]]はどちらも演算機能ですが、適用範囲が異なります。 [[]]は主にリスト内の要素を取得するために使用され、[]はすべてのオブジェクトに適用できますが、リスト内の要素をインデックスで取得することはできません。