访问列表元素的[]和[[]]符号之间的区别 [英] The difference between [] and [[]] notations for accessing the elements of a list

查看:106
本文介绍了访问列表元素的[]和[[]]符号之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R提供了两种访问列表或数据元素的不同方法:框架 - [] [[]] 操作符。



两者有什么区别?

解决方案

R语言定义适用于回答这些类型的问题: / p>





R有三个基本的索引运算符,其语法由以下示例显示


 
x [i]
x [i,j]
x [[i]]
x [[i,j]]
x $ a
x $a



对于向量和矩阵, [[形式很少被使用,尽管它们与[form(例如,它丢弃任何名称或dimnames属性,并且部分匹配用于字符索引)有一些轻微的语义差异)。当使用单个索引索引多维结构时, x [[i]] x [i] 将返回 i 连续元素 x


对于列表,一般通常使用 [[来选择任何单个元素,而 [返回所选元素的列表。


[[ form]只允许使用整数或字符索引选择一个元素,而 允许通过向量进行索引。注意,对于列表,索引可以是向量,并且向量的每个元素依次应用于列表,所选择的组件,该组件的所选组件等等。结果仍然是一个单一的元素。


R provides two different methods for accessing the elements of a list or data.frame- the [] and [[]] operators.

What is the difference between the two? In what situations should I use one over the other?

解决方案

The R Language Definition is handy for answering these types of questions:

R has three basic indexing operators, with syntax displayed by the following examples

    x[i]
    x[i, j]
    x[[i]]
    x[[i, j]]
    x$a
    x$"a"

For vectors and matrices the [[ forms are rarely used, although they have some slight semantic differences from the [ form (e.g. it drops any names or dimnames attribute, and that partial matching is used for character indices). When indexing multi-dimensional structures with a single index, x[[i]] or x[i] will return the ith sequential element of x.

For lists, one generally uses [[ to select any single element, whereas [ returns a list of the selected elements.

The [[ form allows only a single element to be selected using integer or character indices, whereas [ allows indexing by vectors. Note though that for a list, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element.

这篇关于访问列表元素的[]和[[]]符号之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆