# 獲取操作符[[的幫助 ?`[[`
相同點:
兩者作用都是“提取”,當從一個向量或矩陣中提取第3個元素時,兩者結果相同!
> aaa<-c(1,2,3,4,5) > aaa[3] [1] 3 > aaa[[3]] [1] 3
不同點:
當數據不是一個list時,情況就不同了。
[] extracts a list, [[]] extracts elements within the list
The [[ form allows only a single element to be selected using integer or character indices, whereas [ allows indexing by vectors.
> alist <- list(c("a", "b", "c"), c(1,2,3,4), c(8e6, 5.2e9, -9.3e7)) > alist[[1]] [1] "a" "b" "c" > alist[1] [[1]] [1] "a" "b" "c" 看起來結果一樣,但其實數據類型不一樣的: > str(alist[[1]]) chr [1:3] "a" "b" "c" > str(alist[1]) List of 1 $ : chr [1:3] "a" "b" "c"
另一個區別是 [[ 可通過參數“exact”激活模糊匹配,[]則不行。
# 定義list對象 li <- list(name='yiifaa', age=35) # 從list提取元素一定要用[[]] # 模糊匹配到name li[['nam', exact=FALSE]]
R有三個基本的索引操作符,其語法由以下示例顯示
x[i] x[i, j] x[[i]] x[[i, j]] x$a x$"a"對於向量和矩陣,
[[
表單很少使用,盡管它們與表單有一些細微的語義差異[
(例如,它刪除任何名稱或dimnames屬性,並且部分匹配用於字符索引)。使用單個索引索引多維結構時,x[[i]]
或者x[i]
將返回第i
th個順序元素x
。對於列表,通常用於
[[
選擇任何單個元素,而[
返回所選元素的列表。該
[[
表單只允許使用整數或字符索引選擇單個元素,而[
允許通過向量進行索引。請注意,對於列表,索引可以是向量,向量的每個元素依次應用於列表,所選組件,該組件的選定組件等。結果仍然只是一個元素。
ref
https://www.jianshu.com/p/f41642cfb7e1