Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

Using '[' square bracket as a function for lapply in R

I've seen the function lapply used in R to extract elements from matrices that exist in a list of matrices.

E.g. I have a list of 3 (2x2) matrices, and I want to extract element [1,2] from each of those 3 matrices.

The code: list1 = lapply(mylist, '[', 1,2) works just fine. It returns a list with those 3 elements.

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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! 

Now, Have a look at the arguments to lapply:

args(lapply)
# function (X, FUN, ...) 

Everything represented in those dots gets passed on to the function FUN as arguments.

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 "["


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...