Reputation:
I have a function which check for me my list. I have a list with two vectors. instead of repeating my code, I tried to use for
loop. However, the for loop does not work as expected.
Here is my code:
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
Upvotes: 0
Views: 96
Reputation: 24262
I suggest to declare pscale
as matrix:
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
Otherwise, defining pscale
as a list:
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
Upvotes: 1
Reputation: 733
That should work.
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)
}
}
Upvotes: 2