使用“["方括号作为 R 中 lapply 的函数 [英] Using '[' square bracket as a function for lapply in R
问题描述
我已经看到在 R 中使用 lapply
函数从矩阵列表中存在的矩阵中提取元素.
I've seen the function lapply
used in R to extract elements from matrices that exist in a list of matrices.
例如我有一个包含 3 (2x2) 个矩阵的列表,我想从这 3 个矩阵中的每一个中提取元素 [1,2].
E.g. I have a list of 3 (2x2) matrices, and I want to extract element [1,2] from each of those 3 matrices.
代码:list1 = lapply(mylist, '[', 1,2)
工作得很好.它返回一个包含这 3 个元素的列表.
The code: list1 = lapply(mylist, '[', 1,2)
works just fine. It returns a list with those 3 elements.
我正在尝试研究这到底是做什么的.谷歌没有提供帮助,在 R 帮助中使用 ?'['
并不太解释.我不明白 '['
是 R 中的函数,所以代码不直观.
I am trying to research what this is exactly doing. Google hasn't helped and using ?'['
in the R help isn't too explanatory. I don't see how '['
is a function in R, so the code is not intuitive.
推荐答案
方括号实际上是一个函数,它的第一个参数是被子集化的对象.后续参数是该子集的索引.
The square brackets are in fact a function whose first argument is the object being subsetted. Subsequent arguments are the index to that subset.
# For example, if M is a matrix
M[1, 2] # extracts the element at row 1, col 2
# is the same as
`[`(M, 1, 2)
# Try them!
现在,看看 lapply
的参数:
Now, Have a look at the arguments to lapply
:
args(lapply)
# function (X, FUN, ...)
这些点中表示的所有内容都作为参数传递给函数 FUN
.
Everything represented in those dots gets passed on to the function FUN
as arguments.
因此,当 FUN="["
时,"["
的第一个参数是列表的当前元素(被迭代),即对象被子集化.而随后的参数是 "["
Thus, when FUN="["
, the first argument to "["
is the current element of the list (being iterated over), ie, the object being subsetted. While the subsequent arguments are the indexes to "["
这篇关于使用“["方括号作为 R 中 lapply 的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!