Reputation: 138
I have created a matrix of lists of varying length. The length of the lists is determined by elements in a matrix of the same shape.
I need to access elements of the lists.
myMatrix <- matrix(list(), nrow=Sims, ncol=Scens)
for (i in 1:Scens) {
for (j in 1:Sims) {
bin <- list(c(rlnorm(Frequency_matrix[j, i], meanlog=mu[i], sdlog=sigma[i])))
if (Frequency_matrix[j,i] == 0){
myMatrix[j, i] <- list(0)
} else {
myMatrix[j, i] <- bin
}
}
}
The output for element [1, 22]
then appears:
[1] 1665085 1444953 1393626 1076812 2187266
and is of list class. However, the list is of length 1. It appears that the list is getting flattened.
I cannot access the elements of this list. I'd expect to be able to access the elements with:
myMatrix[1,22][[2]]
Using this, I aim to apply rank correlations to the matrix based on the sums of the individual list elements. However, I must be able to access each list element individually as well.
Upvotes: 0
Views: 225
Reputation: 269481
Create plain numeric vectors instead of lists and rather than assigning to myMatrix[i, j]
assign to myMatrix[[i, j]]
like this:
nr <- 4; nc <- 2
myMatrix <- matrix(list(), nr, nc)
for (i in 1:nr) {
for (j in 1:nc) {
myMatrix[[i, j]] <- c(i, j)
}
}
myMatrix[[3, 2]]
## [1] 3 2
Upvotes: 1
Reputation: 1234
Try
myMatrix[1,22][[1]][2]
For the second item in the vector stored in the first list item in the first row and 22nd column of your matrix :)
Upvotes: 0