使用数组填充矩阵条目

时间:2017-12-11 10:23:20

标签: arrays r matrix

我有一个元素载体

p1 p2 p3 p4 ...

我试图从他们那里构建以下矩阵

p1 p2 p3 1  1  1  1  1  1  1   1   1  ...
p1 p2 p3 p4 p5 p6 1  1  1  1   1   1  ...
p1 p2 p3 p4 p5 p6 p7 p8 p9 1   1   1  ...
p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12  ...

等等。我试着用

blockmatrix

例如

p<-1:6
A<-head(p,3)
B<-c(1,1,1)
D<-tail(p,3)
blockmatrix(names=c("A","B","C","D"),A=A,C=B,B=A,D=D,dim=c(2,2))

但问题是获得更大尺寸的块矩阵。 (此代码仅适用于两个块,对于三个块,我将在字段中添加其他标签&#34;名称&#34;,依此类推四个块,五个......)

这是另一种解决方案,在阅读答案后撰写:

 x<-2:10
 mat<- t(replicate(3, x))
 mat[col(mat)>3*row(mat)] <- 1

3 个答案:

答案 0 :(得分:3)

这将为您提供数据帧输出,但您可以将其转换为矩阵。

library(dplyr)
library(tidyr)

# example vector
x = c(10,11,12,13,14,15)

expand.grid(id_row=1:length(x), x=x) %>%       # combine vector values and a sequence of numbers (id = row positions)
  group_by(id_row) %>%                         # for each row position
  mutate(id_col = row_number()) %>%            # create a vector of column positions (needed for reshaping later)
  ungroup() %>%                                # forget the grouping
  mutate(x = ifelse(id_col > id_row, 1, x),    # replace values with 1 where necessary
         id_col = paste0("Col_", id_col)) %>%  # update names of this variable
  spread(id_col, x) %>%                        # reshape data
  select(-id_row)                              # remove unnecessary column

# # A tibble: 6 x 6
#   Col_1 Col_2 Col_3 Col_4 Col_5 Col_6
# * <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1    10     1     1     1     1     1
# 2    10    11     1     1     1     1
# 3    10    11    12     1     1     1
# 4    10    11    12    13     1     1
# 5    10    11    12    13    14     1
# 6    10    11    12    13    14    15

答案 1 :(得分:3)

目前尚不清楚所有条件。这是一个base R选项

m1 <- t(replicate(length(x), x))
m1[upper.tri(m1)] <- 1
m1
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   10    1    1    1    1    1
#[2,]   10   11    1    1    1    1
#[3,]   10   11   12    1    1    1
#[4,]   10   11   12   13    1    1
#[5,]   10   11   12   13   14    1
#[6,]   10   11   12   13   14   15

数据

x <- c(10,11,12,13,14,15)

答案 2 :(得分:2)

这应该在Base R

中为您提供所需的输出
a<- c("p1","p2","p3","p4","p5","p6","p7","p8","p9","p10","p11","p12")
lena <- length(a)
b<- matrix(data=rep(a,lena%/%3),nrow=lena%/%3,ncol = lena,byrow=T)

for (i in (1:(nrow(b)-1)))
{ 
  for (j in ((3*i+1):ncol(b)))
  { 
      b[i,j] <- 1
  }
}
相关问题