制作列的矩阵意味着

时间:2016-06-04 13:34:20

标签: r

我的数据中有一个列向量的向量,如下所示:

cmean <- c(v1=50.99013605,  v2=13.27823129, v3=67.83265306, v4=25.88299320)

    v1             v2              v3              v4 
    50.99013605    13.27823129     67.83265306     25.88299320 

然后我想从中创建一个矩阵,其中所有列都只是列的重复。因此我希望它看起来像这样:

    50.99013605    13.27823129     67.83265306     25.88299320 
    50.99013605    13.27823129     67.83265306     25.88299320 
    50.99013605    13.27823129     67.83265306     25.88299320 
    50.99013605    13.27823129     67.83265306     25.88299320 

我使用rep尝试了很多,但是我在矩阵中以这种格式很好地把它放进去了。最方便的方法是什么?

3 个答案:

答案 0 :(得分:9)

您可以将byrow参数用于matrix。例如:

> x <- 1:4
> matrix(x, 4, 4, TRUE)
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    1    2    3    4
[3,]    1    2    3    4
[4,]    1    2    3    4

如果您未通过TRUE,则默认情况下会按列填充矩阵:

> matrix(x, 4, 4)
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    2    2    2    2
[3,]    3    3    3    3
[4,]    4    4    4    4

答案 1 :(得分:4)

在使用dim<-复制'v1'后,我们可以使用col指定维度。

`dim<-`(v1[col(d2)], dim(d2))
#         [,1]     [,2]     [,3]     [,4]
#[1,] 50.99014 13.27823 67.83265 25.88299
#[2,] 50.99014 13.27823 67.83265 25.88299
#[3,] 50.99014 13.27823 67.83265 25.88299
#[4,] 50.99014 13.27823 67.83265 25.88299

或使用replicate

do.call(rbind, replicate(nrow(d2), v1, simplify=FALSE))
#        v1       v2       v3       v4
#[1,] 50.99014 13.27823 67.83265 25.88299
#[2,] 50.99014 13.27823 67.83265 25.88299
#[3,] 50.99014 13.27823 67.83265 25.88299
#[4,] 50.99014 13.27823 67.83265 25.88299

或紧凑型选项

(d2/d2)*v1[col(d2)]

如果我们使用dplyr

library(dplyr)
d2 %>%
    mutate_each(funs(mean))

其中'd2'是初始数据集,'v1'是其列。

答案 2 :(得分:3)

以下是rep()

的解决方案
cmean <- c(v1=50.99013605,  v2=13.27823129, v3=67.83265306, v4=25.88299320)
M <- 5 # number of rows
matrix(rep(cmean, each=M), M)
#> matrix(rep(cmean, each=M), M)
#         [,1]     [,2]     [,3]     [,4]
#[1,] 50.99014 13.27823 67.83265 25.88299
#[2,] 50.99014 13.27823 67.83265 25.88299
#[3,] 50.99014 13.27823 67.83265 25.88299
#[4,] 50.99014 13.27823 67.83265 25.88299
#[5,] 50.99014 13.27823 67.83265 25.88299

如果要复制名称,可以执行以下操作:

x <- matrix(rep(cmean, each=M), M)
colnames(x) <- names(cmean)