[英]Default matrix number of columns and rows in R
In R, I can create a matrix with matrix()
, which has the function definition: 在R中,我可以使用
matrix()
创建一个具有函数定义的matrix()
:
function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
{ ... }
This suggests that the default value for number of rows ( nrow
) and columns ( ncol
) are 1. 这表明,对于行数(数量的默认值
nrow
)(和列ncol
)是1。
So why does the following break? 那么,为什么以下中断? Why does specifying the same default values of
1
result in a different matrix? 为什么指定相同的默认值
1
导致矩阵不同?
> matrix(1:9)
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
> matrix(1:9, ncol=1, nrow=1)
[,1]
[1,] 1
The user-facing base::matrix
calls an internal function : 面向用户的
base::matrix
调用内部函数 :
matrix
# function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
# {
# if (is.object(data) || !is.atomic(data))
# data <- as.vector(data)
# .Internal(matrix(data, nrow, ncol, byrow, dimnames, missing(nrow),
# missing(ncol)))
# }
# <bytecode: 0x000000000b802e88>
# <environment: namespace:base>
In particular, note that the last two arguments passed to the internal function are flags indicating if the row and / or column dimensions were specified: missing(nrow), missing(ncol)
. 特别要注意,传递给内部函数的最后两个参数是指示是否指定行和/或列尺寸的标志:
missing(nrow), missing(ncol)
。 The fact that these parameters have default values does not preclude them from being "missing". 这些参数具有默认值的事实并不排除它们“丢失”。 For example,
例如,
f <- function(x = 1, y = 2) {
cat(sprintf(
"missing(x): %s\nmissing(y): %s\n",
missing(x),
missing(y)
))
}
f()
# missing(x): TRUE
# missing(y): TRUE
Since the "missing-ness" of these arguments is not affected by the fact that they have default values, that logic can be handled independently, as is done here . 由于这些参数的“缺失性”不受它们具有默认值的事实的影响,因此可以像此处所做的那样独立处理该逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.