问题
This a question about R's internals. I am curious if someone could explain how the following call works.
# Let's just work with part of the iris data
data(iris)
df <- iris[1:10, 1:4]
# Now the question
1 - df
Does R create another matrix of equivalent dimensions? Does it loop over all elements? How is R subtracting a matrix from an integer?
回答1:
Note that your example is a data.frame and not a matrix. I will refer to the data.frame case.
An S3 method is dispatched by the Ops group generic (see methods("Ops")). The relevant method is Ops.data.frame. Here are some excerpts with comments added by me:
#create an unevaluated function call
FUN <- get(.Generic, envir = parent.frame(), mode = "function")
f <- if (unary)
quote(FUN(left))
else quote(FUN(left, right))
#...
#a lot of checking and preparations
#...
#loop over the columns, create the function input and evaluate the function call
for (j in seq_along(cn)) {
left <- if (!lscalar)
e1[[j]]
else e1
right <- if (!rscalar)
e2[[j]]
else e2
value[[j]] <- eval(f)
}
In case of the arguments to - being an integer vector and an integer matrix, both are treated as an integer vector, but .Primitive("-") preserves attributes, which includes the dim atribute of the matrix. See also help("-").
来源:https://stackoverflow.com/questions/26781311/how-r-subtracts-a-matrix-from-an-integer