gpt4 book ai didi

r - 访问列表或数据帧元素时括号 [ ] 和双括号 [[ ]] 之间的区别

转载 作者:行者123 更新时间:2023-12-03 03:54:52 27 4
gpt4 key购买 nike

R 提供了两种不同的方法来访问列表或 data.frame 的元素:[][[]]

两者之间有什么区别,什么时候应该使用其中一种而不是另一种?

最佳答案

R 语言定义可以方便地回答这些类型的问题:

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.

关于r - 访问列表或数据帧元素时括号 [ ] 和双括号 [[ ]] 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1169456/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com