全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 R语言论坛
8107 2
2011-11-10
在实验设计时经常碰到这样的矩阵。该矩阵是把一个单位矩阵的每一行重复一定的次数。      [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    0    0
[2,]    1    0    0    0    0
[3,]    1    0    0    0    0
[4,]    0    1    0    0    0
[5,]    0    1    0    0    0
[6,]    0    1    0    0    0
[7,]    0    1    0    0    0
[8,]    0    1    0    0    0
[9,]    0    0    1    0    0
[10,]    0    0    1    0    0
[11,]    0    0    0    1    0
[12,]    0    0    0    1    0
[13,]    0    0    0    1    0
[14,]    0    0    0    1    0
[15,]    0    0    0    0    1


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我的做法是先写了个函数,输入是一个给定的矩阵和每一行要重复的次数,输出则是想要的矩阵。
repMat <- function(x, each = NULL) {
    if (is.null(each)) return(x)
    n <- nrow(x)
    if (length(each) != n) stop("Number of rows in x should be equal to the length of each!")
    res <- NULL
    for (i in 1:n) {
        currentline <- matrix(rep(x[i, ], each), nrow = each, byrow = TRUE)
        res <- rbind(res, currentline)
    }
    return(res)
}

然后
x <- diag(5)
repMat(x, c(3,5,2,4,1))
就可以了。


不知道还有没有更方便的方法。
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2011-11-10 21:48:13
自问自答
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2011-11-11 06:42:34
Here is just another way of looking at the question. Can not really say it's easier...
复制代码
Certainly you can write a function with this method.
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2011-11-11 06:44:15
Here is just another way of looking at the question. Can not really say it's easier...
复制代码
Certainly you can write a function with this method.
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2011-11-11 06:49:50
Here is just another way of looking at the question. Can not really say it's easier...
复制代码
Certainly you can write a function with this method.
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2011-11-12 00:15:40
偷懒法
复制代码
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群