簡體   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