关于r:用于访问列表或数据框元素的括号[]和双括号[[]]之间的区别 |
您所在的位置:网站首页 › r语言中列表和tibble有什么区别吗 › 关于r:用于访问列表或数据框元素的括号[]和双括号[[]]之间的区别 |
R提供了两种不同的方法来访问列表或data.frame的元素-[]和[[]]运算符。 两者有什么区别? 在什么情况下我应该使用另一个? R语言定义可轻松回答以下类型的问题: http://cran.r-project.org/doc/manuals/R-lang.html#IndexingR has three basic indexing operators, with syntax displayed by the following examples 123456 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. 相关讨论 使用[[vs [用单个数字vs向量进行索引]的背后原因是什么?为什么不同时使用[我猜您可以使用[[返回单个条目,并且[具有一个索引返回长度为1的列表...但是为什么不让[返回具有一个索引而不是列表的单个入口?为什么您要返回长度为1的列表? @wordsforthewise,在编程时,您可以具有要用于索引的长度不确定的向量。使[始终返回一个列表意味着无论v的长度如何,您都为x[v]获得相同的输出类。例如,可能要在列表的子集lapply(x[v], fun)上lapply。如果[将删除长度为1的向量的列表,则当v的长度为1时,这将返回错误。 我认为这可以更清楚地解释,adv-r.had.co.nz / Subsetting.html两种方法之间的显着区别在于,它们在用于提取时返回的对象的类别,以及它们是否可以接受一定范围的值,或者在赋值期间仅接受单个值。 考虑以下列表中数据提取的情况: 1foo r[[c(1,2,3)]] Error in r[[c(1, 2, 3)]] : recursive indexing failed at level 2 > r[[c("foo","far")]] Error in r[[c("foo","far")]] : subscript out of bounds 相关讨论 不赞成使用,是因为"传递矢量...将导致错误,只是因为它不是为满足这种需要而构建的",这是不正确的;看到我的新答案。 拒绝投票,是因为它提出了强有力的主张,例如"双支架永远不会返回列表"。这不是事实-如果我们有一个对象是列表列表,则双括号将返回另一个列表。为了帮助新手克服手动迷雾,将[[ ... ]]表示法视为折叠功能可能会有所帮助-换句话说,这就是当您只想从命名矢量,列表或数据框"获取数据"时。如果要使用这些对象中的数据进行计算,则最好这样做。这些简单的例子将说明。 123(x |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |