R提供了两种不同的方法来访问list或data.frame中的元素:[]和[[]]。
这两者之间的区别是什么,什么时候我应该使用其中一个而不是另一个?
R提供了两种不同的方法来访问list或data.frame中的元素:[]和[[]]。
这两者之间的区别是什么,什么时候我应该使用其中一个而不是另一个?
当前回答
双括号访问列表元素,而单括号返回一个包含单个元素的列表。
lst <- list('one','two','three')
a <- lst[1]
class(a)
## returns "list"
a <- lst[[1]]
class(a)
## returns "character"
其他回答
R语言定义对于回答这些类型的问题很方便:
http://cran.r-project.org/doc/manuals/R-lang.html#Indexing
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.
双括号访问列表元素,而单括号返回一个包含单个元素的列表。
lst <- list('one','two','three')
a <- lst[1]
class(a)
## returns "list"
a <- lst[[1]]
class(a)
## returns "character"
请参考以下详细说明。
我使用了R中的内置数据框架,称为mtcars。
> mtcars
mpg cyl disp hp drat wt ...
Mazda RX4 21.0 6 160 110 3.90 2.62 ...
Mazda RX4 Wag 21.0 6 160 110 3.90 2.88 ...
Datsun 710 22.8 4 108 93 3.85 2.32 ...
............
表的顶部行称为标题,其中包含列名。之后的每条水平线表示一个数据行,它以行名开始,然后跟着实际数据。 一行中的每个数据成员称为一个单元格。
单个方括号“[]”运算符
要检索单元格中的数据,可以在单个方括号“[]”操作符中输入它的行坐标和列坐标。这两个坐标用逗号分隔。换句话说,坐标以行位置开始,然后以逗号结尾,以列位置结束。顺序很重要。
例1:-这是mtcars的第一行第二列的单元格值。
> mtcars[1, 2]
[1] 6
例2:-此外,我们可以使用行名和列名来代替数字坐标。
> mtcars["Mazda RX4", "cyl"]
[1] 6
双方括号“[[]]”操作符
我们用双方括号“[[]]”操作符引用数据帧列。
例1:-为了检索内置数据集mtcars的第九列向量,我们编写mtcars[[9]]。
山地车[[9]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...
例2:-我们可以通过名称检索相同的列向量。
MTCARS[[“AM”]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...
为了帮助新手在手动迷雾中导航,看看[[…]]]符号作为一个折叠函数-换句话说,当你只是想从一个命名向量,列表或数据帧中“获取数据”时。如果您想使用来自这些对象的数据进行计算,那么这样做是很好的。这些简单的例子将说明。
(x <- c(x=1, y=2)); x[1]; x[[1]]
(x <- list(x=1, y=2, z=3)); x[1]; x[[1]]
(x <- data.frame(x=1, y=2, z=3)); x[1]; x[[1]]
从第三个例子来看
> 2 * x[1]
x
1 2
> 2 * x[[1]]
[1] 2
[]提取列表,[[]]提取列表中的元素
alist <- list(c("a", "b", "c"), c(1,2,3,4), c(8e6, 5.2e9, -9.3e7))
str(alist[[1]])
chr [1:3] "a" "b" "c"
str(alist[1])
List of 1
$ : chr [1:3] "a" "b" "c"
str(alist[[1]][1])
chr "a"