矩阵和向量形式的数据点数 [英] The number of data points in matrix and vector forms
问题描述
假设X
包含1000列带有m
列的行,其中m
等于3,如下所示:
Supposed that X
contains 1000 rows with m
columns, where m
equal to 3 as follows:
set.seed(5)
X <- cbind(rnorm(1000,0,0.5), rnorm(1000,0,0.5), rnorm(1000,0,0.5))
执行变量选择,然后将在执行下一个操作之前检查条件,如下所示.
Variable selection is performed, then the condition will be checked before performing the next operation as follows.
if(nrow(X) < 1000){print(a+b)}
,其中a
是5,b
是15,因此如果nrow(X) < 1000
是TRUE
,则将打印20.
但是,如果X
恰好是一个矢量,因为只选择了一个列,
,where a
is 5 and b
is 15, so if nrow(X) < 1000
is TRUE
, then 20 will be printed out.
However, in case that X
happens to be a vector because only one column is selected,
当X可以是矩阵或向量时,如何检查数据点的数量?
我能想到的是
if(is.matrix(X)){
n <- nrow(X)
} else {
n <- length(X)}
if(n < 1000){print(a+b)}
有人有更好的主意吗?
谢谢
推荐答案
两种情况下都可以使用NROW
.来自?NROW
You can use NROW
for both cases. From ?NROW
nrow
和ncol
返回x
中存在的行数或列数.NCOL
和NROW
将向量作为1列矩阵进行相同的处理.
nrow
andncol
return the number of rows or columns present inx
.NCOL
andNROW
do the same treating a vector as 1-column matrix.
因此,即使x
是数组,向量或数据帧NROW
,即使将子集放到一个向量中,它也将其视为单列矩阵.
So that means that even if the subset is dropped down to a vector, as long as x
is an array, vector, or data frame NROW
will treat it as a one-column matrix.
sub1 <- X[,2:3]
is.matrix(sub1)
# [1] TRUE
NROW(sub1)
# [1] 1000
sub2 <- X[,1]
is.matrix(sub2)
# [1] FALSE
NROW(sub2)
# [1] 1000
所以if(NROW(X) < 1000L) a + b
应该起作用,而不管X
是矩阵还是向量.我在下面使用<=
,因为在您的示例中X
正好有1000行.
So if(NROW(X) < 1000L) a + b
should work regardless of whether X
is a matrix or a vector. I use <=
below, since X
has exactly 1000 rows in your example.
a <- 5; b <- 15
if(NROW(sub1) <= 1000L) a + b
# [1] 20
if(NROW(sub2) <= 1000L) a + b
# [1] 20
第二种选择是在选择变量时使用drop=FALSE
.当子集只有一列时,这将使子集保持矩阵.这样您就可以放心使用nrow
了.
A second option would be to use drop=FALSE
when you make the variable selection. This will make the subset remain a matrix when the subset is only one column. This way you can use nrow
with no worry. An example of this is
X[, 1, drop = FALSE]
这篇关于矩阵和向量形式的数据点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!