繁体   English   中英

用 r 中向量的顺序值替换列表中每个矩阵中的特定位置值

[英]replacing specific positional value in each matrix within a list, with sequential values from a vector in r

我试图用向量中的每个顺序值替换列表中每个矩阵的特定值(按位置)。 从下面的代码中,我想在列表中的每个矩阵中替换值 2(由 position,所以不要简单地将所有 2 替换为...),每个值从 one.to.two.s 是一个数字向量。 作为扩展,如果向量的长度为 50 并且列表的长度为 100,我希望能够重复 one.to.two.s 序列。我在这里有一个 forloop 不起作用,但相信这可以lapply 也以某种方式处理。 在此先感谢您的帮助。

 A <- lapply(1:50, function(x)  # construct list of matrices
    matrix(c(0, 0, 0, 0,
             2, 0, 0, 0,
             0, 0, 0, 0,
             0, 0, 0, 1), nrow = 4,ncol=4, byrow = TRUE, ))
  Anew <-A

  one.to.two.s <- c(seq(from = 0.40, to = 0.89,by=0.01))
  
  for(t in 1:length(Anew)) {
    Anew[[t]][2,1] <- one.to.two.s
  }

我相信这就是您正在寻找的。

# use replicate() instead of lapply()
B <- 50L
A <- replicate(B*2.1,
               matrix(c(0, 0, 0, 0,
                        2, 0, 0, 0,
                        0, 0, 0, 0,
                        0, 0, 0, 1), nrow = 4,ncol=4, byrow = TRUE),
               simplify = FALSE)
Anew <- A
one.to.two.s <- seq(from = 0.40, to = 0.89, by = 0.01)

# loop over all elements in Anew
for (t in seq_along(Anew)) {
  Anew[[t]][2,1] <- one.to.two.s[
    seq_len(length(Anew) + 2L) %% (length(one.to.two.s) + 1L)
  ][t]
}

# > head(sapply(Anew, '[', 2))
# [1] 0.40 0.41 0.42 0.43 0.44 0.45

# > tail(sapply(Anew, '[', 2))
# [1] 0.89 0.40 0.41 0.42 0.43 0.44

如果您的列表比向量长,您可以尝试以下for循环

for(t in 1:length(Anew)) {
    Anew[[t]][2,1] <- one.to.two.s[(t-1)%%length(one.to.two.s)+1]
  }

我也忘了在替换的末尾添加 [t]。 也可以提前重复一个向量。

for(t in 1:length(Anew)) {
    Anew[[t]][2,1] <- one.to.two.s
  }

反而变成

for(t in 1:length(Anew)) {
    Anew[[t]][2,1] <- one.to.two.s[t]
  }

使用比length(A)短的one.to.two.s示例,您可以使用replength.out使其长度正确,然后在该向量和A上使用Map创建Anew

one.to.two.s <- seq(from = 0.4, to = 0.8, by = 0.01)

Anew <- Map(function(A, x) {
  A[2, 1] <- x
  A
}, A, rep(one.to.two.s, length.out = length(A)))

代表 package (v2.0.1) 于 2022 年 1 月 27 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM