【问题标题】:If there is the same nrows cbind two datas如果有相同的nrows cbind 两个数据
【发布时间】:2014-03-12 13:58:02
【问题描述】:

如何告诉 R 仅当两个矩阵的行数相同时才 cbind ?

我知道我可以手动检查。

【问题讨论】:

  • if (nrow(X)==nrow(Y)) Z

标签: r cbind


【解决方案1】:

制作一个函数,比如:

ckbind = function (a, b) 
{
    a = as.matrix(a)
    b = as.matrix(b)
    if (nrow(a) == nrow(b)) {
        return(cbind(a, b))
    } else {
        stop("Differing number of rows")
    }
}

注意矩阵转换,因此它适用于向量。测试:

> ckbind(1:3,2:4)
     [,1] [,2]
[1,]    1    2
[2,]    2    3
[3,]    3    4
> ckbind(1:3,2:6)
Error in ckbind(1:3, 2:6) : Differing number of rows

并检查它是否适用于矩阵:

> ckbind( ckbind(1:3,2:4), ckbind(3:5,4:6))
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    2    3    4    5
[3,]    3    4    5    6

【讨论】:

    猜你喜欢
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    相关资源
    最近更新 更多