如何在 R 中按矩阵列填充向量?

  • 本文关键字:阵列 填充 向量 r
  • 更新时间 :
  • 英文 :


假设我有以下矩阵:

mat <- matrix(0L,61,5)
mat[,1] <- seq(0.7,60.7,1)
mat[,2] <- seq(0.5,60.5,1)
mat[,3] <- seq(0.4,60.4,1)
mat[,4] <- seq(0.1,60.1,1)
mat[,5] <- seq(0.9,60.9,1)

和以下向量:

Vec1: 0   0   0   0   0  20   0   0   0   0   0   0   0  20   0   0   0   0   0   0  20 120   0
Vec2: 0   0   0   0   0   0   0  20   0   0   0   0   0  20   0   0   0   0   0   0  20   0 120
Vec3: 0   0   0   0   0   0   0  20   0   0  20   0   0   0  20 120   0   0   0   0   0   0   0
...

现在,如果向量不为零,我想用矩阵值(mat[,1] -> vec1(填充向量。 为简单起见,它是一个示例,所以这样的事情不起作用,因为我不知道值和零频率之间的距离。但是,这应该是向量 1 的解决方案:

Vec1 <- c(rep(0,5),mat[1,1],rep(0,7),mat[2,1],rep(0,6),mat[3,1],mat[4,1],0)
> Vec1 0.0 0.0 0.0 0.0 0.0 0.7 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.7 0.0 0.0 0.0 0.0 0.0 0.0 2.7 3.7 0.0

以下是从基本 Rmgetlapply的方法:

veclist <- mget(ls(pattern = "Vec[0-9]+"))
lapply(names(veclist),function(x){
ind <- as.integer(gsub(".*([0-9]+)","\1",x))
result <- veclist[[x]]
toreplace <- which(result != 0)
result[toreplace] <- mat[seq_along(toreplace),ind]
result})
[[1]]
[1] 0.0 0.0 0.0 0.0 0.0 0.7 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.7 0.0 0.0 0.0 0.0 0.0 0.0 2.7 3.7 0.0
[[2]]
[1] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.5 0.0 0.0 0.0 0.0 0.0 1.5 0.0 0.0 0.0 0.0 0.0 0.0 2.5 0.0 3.5
[[3]]
[1] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.4 0.0 0.0 1.4 0.0 0.0 0.0 2.4 3.4 0.0 0.0 0.0 0.0 0.0 0.0 0.0

示例数据

Vec1 <- c(0L, 0L, 0L, 0L, 0L, 20L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 20L, 0L, 
0L, 0L, 0L, 0L, 0L, 20L, 120L, 0L)
Vec2 <- c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 20L, 0L, 0L, 0L, 0L, 0L, 20L, 0L, 
0L, 0L, 0L, 0L, 0L, 20L, 0L, 120L)
Vec3 <- c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 20L, 0L, 0L, 20L, 0L, 0L, 0L, 20L, 
120L, 0L, 0L, 0L, 0L, 0L, 0L, 0L)

最新更新