基于R中的向量重复矩阵的行
Repeating rows of a matrix based on a vector in R
我想根据向量 (rep_vec
) 的值重复矩阵 (M
) 的行。在这种情况下,第一行将重复一次,第二行重复两次,第三行重复三次。
M <- matrix(1:9, nrow = 3,ncol = 3)
#> M
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 2 5 8
# [3,] 3 6 9
rep_vec <- matrix(1:3, nrow = 3,ncol = 1)
#> rep_vec
# [,1]
#[1,] 1
#[2,] 2
#[3,] 3
我设法使用 lapply
一个函数 (rep_matrix
) 来做到这一点,只是为了避免 for 循环结构。但是,我对我的解决方案不太满意,我认为我应该遗漏一些东西,因为对我来说这似乎是一个没有单行解决方案的微不足道的问题。
rep_matrix <- function(i){
return(rep(x= M[,i], times =rep_vec))
}
list_repmatrix <- lapply(seq_along(1:ncol(M)),
rep_matrix)
rep_matrix <- matrix(unlist(list_repmatrix),
ncol = ncol(M) ,
byrow=FALSE)
#> rep_matrix
# [,1] [,2] [,3]
#[1,] 1 4 7
#[2,] 2 5 8
#[3,] 2 5 8
#[4,] 3 6 9
#[5,] 3 6 9
#[6,] 3 6 9
有没有人有更elegant/faster的解决方案或者可以推荐更好的方法?
您不需要单独重复每一列 - 您可以使用具有重复行索引的子集来重复整行:
## We use this as the row indices
## This will work whether `rep_vec` is a 1-column matrix
## Or if it is a vector (as implied by its name)
rep(seq_along(rep_vec), rep_vec)
[1] 1 2 2 3 3 3
M[rep(seq_along(rep_vec), rep_vec), ]
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 2 5 8
# [3,] 2 5 8
# [4,] 3 6 9
# [5,] 3 6 9
# [6,] 3 6 9
你可以这样做:
M[rep(1:3, 1:3),]
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 2 5 8
#> [4,] 3 6 9
#> [5,] 3 6 9
#> [6,] 3 6 9
是否有效:使用 tidyverse。
library(dplyr)
library(tidyr)
as.matrix(uncount(as_tibble(M),rep_vec))
V1 V2 V3
[1,] 1 4 7
[2,] 2 5 8
[3,] 2 5 8
[4,] 3 6 9
[5,] 3 6 9
[6,] 3 6 9
>
我想根据向量 (rep_vec
) 的值重复矩阵 (M
) 的行。在这种情况下,第一行将重复一次,第二行重复两次,第三行重复三次。
M <- matrix(1:9, nrow = 3,ncol = 3)
#> M
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 2 5 8
# [3,] 3 6 9
rep_vec <- matrix(1:3, nrow = 3,ncol = 1)
#> rep_vec
# [,1]
#[1,] 1
#[2,] 2
#[3,] 3
我设法使用 lapply
一个函数 (rep_matrix
) 来做到这一点,只是为了避免 for 循环结构。但是,我对我的解决方案不太满意,我认为我应该遗漏一些东西,因为对我来说这似乎是一个没有单行解决方案的微不足道的问题。
rep_matrix <- function(i){
return(rep(x= M[,i], times =rep_vec))
}
list_repmatrix <- lapply(seq_along(1:ncol(M)),
rep_matrix)
rep_matrix <- matrix(unlist(list_repmatrix),
ncol = ncol(M) ,
byrow=FALSE)
#> rep_matrix
# [,1] [,2] [,3]
#[1,] 1 4 7
#[2,] 2 5 8
#[3,] 2 5 8
#[4,] 3 6 9
#[5,] 3 6 9
#[6,] 3 6 9
有没有人有更elegant/faster的解决方案或者可以推荐更好的方法?
您不需要单独重复每一列 - 您可以使用具有重复行索引的子集来重复整行:
## We use this as the row indices
## This will work whether `rep_vec` is a 1-column matrix
## Or if it is a vector (as implied by its name)
rep(seq_along(rep_vec), rep_vec)
[1] 1 2 2 3 3 3
M[rep(seq_along(rep_vec), rep_vec), ]
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 2 5 8
# [3,] 2 5 8
# [4,] 3 6 9
# [5,] 3 6 9
# [6,] 3 6 9
你可以这样做:
M[rep(1:3, 1:3),]
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 2 5 8
#> [4,] 3 6 9
#> [5,] 3 6 9
#> [6,] 3 6 9
是否有效:使用 tidyverse。
library(dplyr)
library(tidyr)
as.matrix(uncount(as_tibble(M),rep_vec))
V1 V2 V3
[1,] 1 4 7
[2,] 2 5 8
[3,] 2 5 8
[4,] 3 6 9
[5,] 3 6 9
[6,] 3 6 9
>