使用 lapply 和 seq_along 的矩阵索引
Matrix indexing with lapply and seq_along
lapply
未按预期工作。我得到了以下功能:
testing <- function(x){
x <- lapply(seq_along(x), function(i) x[[i]][,2] <- c(88,88,88))
return(x)
}
和测试矩阵列表:
xl <- list(matrix(1:9,3,3),matrix(2:10,3,3))
输出为:
[[1]]
[1] 88 88 88
[[2]]
[1] 88 88 88
为什么会这样?我希望第二列每列替换为 88,但矩阵不会替换为 88 的向量。我一定是漏掉了什么。
你需要
testing <- function(x){
lapply(seq_along(x), function(i) {x[[i]][,2] <- 88
x[[i]]})}
testing(list)
#[[1]]
# [,1] [,2] [,3]
#[1,] 1 88 7
#[2,] 2 88 8
#[3,] 3 88 9
#[[2]]
# [,1] [,2] [,3]
#[1,] 2 88 8
#[2,] 3 88 9
#[3,] 4 88 10
或者我们遍历 list
,将第 2 列更改为 88 和 return 列表元素。
lapply(list, function(x) {x[,2] <- 88; x})
或者如@Frank 所述,我们可以使用 for
循环并将每个 list
元素的第二列分配为 88。
for (j in seq_along(list)) list[[j]][, 2] <- 88
lapply
未按预期工作。我得到了以下功能:
testing <- function(x){
x <- lapply(seq_along(x), function(i) x[[i]][,2] <- c(88,88,88))
return(x)
}
和测试矩阵列表:
xl <- list(matrix(1:9,3,3),matrix(2:10,3,3))
输出为:
[[1]]
[1] 88 88 88
[[2]]
[1] 88 88 88
为什么会这样?我希望第二列每列替换为 88,但矩阵不会替换为 88 的向量。我一定是漏掉了什么。
你需要
testing <- function(x){
lapply(seq_along(x), function(i) {x[[i]][,2] <- 88
x[[i]]})}
testing(list)
#[[1]]
# [,1] [,2] [,3]
#[1,] 1 88 7
#[2,] 2 88 8
#[3,] 3 88 9
#[[2]]
# [,1] [,2] [,3]
#[1,] 2 88 8
#[2,] 3 88 9
#[3,] 4 88 10
或者我们遍历 list
,将第 2 列更改为 88 和 return 列表元素。
lapply(list, function(x) {x[,2] <- 88; x})
或者如@Frank 所述,我们可以使用 for
循环并将每个 list
元素的第二列分配为 88。
for (j in seq_along(list)) list[[j]][, 2] <- 88