我有一个功能可以检查我的列表。我有一个包含两个向量的列表。我尝试使用for
循环,而不是重复我的代码。但是,for循环不能按预期工作。
这是我的代码:
x <- c(2,3,4,5)
y <- c(2,4,6,7)
z <- list(x,y)
pscale <- numeric()
pscale <- list()
for(i in 1:4){#length of my vector
for(j in 1:2){#length of z
pscale[[j]][[i]] <- ifelse(z[[j]][[i]] %in% c(2,9,10),0.01,1)
}
}
Error in `*tmp*`[[j]] : subscript out of bounds
答案 0 :(得分:2)
这应该有效。
x <- c(2,3,4,5)
y <- c(2,4,6,7)
z <- list(x,y)
pscale <- list()
length(pscale) <- 2 # set length to the number of vectors
for(i in 1:4){#length of my vector
for(j in 1:2){#length of z
pscale[[j]][i] <- ifelse(z[[j]][i] %in% c(2,9,10),0.01,1)
}
}
答案 1 :(得分:1)
我建议将pscale
声明为矩阵:
x <- c(2,3,4,5)
y <- c(2,4,6,7)
z <- list(x,y)
pscale <- matrix(rep(NA,length(x)*length(z)), length(z), length(x))
for(i in 1:4) {
for(j in 1:2) {
pscale[j,i] <- ifelse(z[[j]][[i]] %in% c(2,9,10), 0.01, 1)
}
}
pscale
# [,1] [,2] [,3] [,4]
# [1,] 0.01 1 1 1
# [2,] 0.01 1 1 1
否则,将pscale
定义为列表:
x <- c(2,3,4,5)
y <- c(2,4,6,7)
z <- list(x,y)
pscale <- vector(length(z), mode="list")
for(i in 1:4) {
for(j in 1:2) {
pscale[[j]][[i]] <- ifelse(z[[j]][[i]] %in% c(2,9,10), 0.01, 1)
}
}
pscale
# [[1]]
# [1] 0.01 1.00 1.00 1.00
#
# [[2]]
# [1] 0.01 1.00 1.00 1.00