Question

I'm trying to use lapply to transform a list of vectors into a list of matrices.

I'm afraid I haven't been able to find anything to help in my searches!

I know this could be resolved by looping over the length of the list but I've been trying to change my code to avoid loops wherever possible.

The real world example has a much larger span than the toy example below so I'm trying to write efficient code.

SparseIndicies <- matrix(0, 100, 4)

SparseIndicies[, 1] <- rep(1:5, 20) #Assign a group (this is what we want to partition     on)
SparseIndicies[, 2] <- sample(1:10, 100, replace=TRUE)
SparseIndicies[, 3] <- sample(1:10, 100, replace=TRUE)
SparseIndicies[, 4] <- runif(100, 0, 1)

#Above replicates my data structure, albeit randomly

TransitionIndicies <- split(SparseIndicies, as.factor(SparseIndicies[, 1]))
#We now have a list of transition values for each 'group' - though this is now in vector format


#We can do it explicitly for each list item
FirstTransitionIndicies <- matrix(TransitionIndicies[[1]], nrow=20, ncol=4)

#The below falls over with:
#Error in match.fun(FUN) : 
#  'matrix(TransitionIndicies, nrow = 20, ncol = 4)' is not a function, character or symbol

NewTransitionIndicies <- lapply(TransitionIndicies, matrix(TransitionIndicies, nrow=20, ncol=4))

FYI: The 2nd and 3rd column of the above is used to create a sparse matrix with the value of the fourth column.

FirstTransitionMatrix <- sparseMatrix(FirstTransitionIndicies[, 2], FirstTransitionIndicies[, 3], x=FirstTransitionIndicies[, 4]) 

Many thanks for any help you can offer, or resources you can point me towards!

Was it helpful?

Solution

I think you want to use:

lapply(TransitionIndicies, function(x) matrix(x, nrow=20, ncol=4))

You weren't specifying a function to lapply, here the error message was pretty informative.

You could also use (less explicitly):

lapply(TransitionIndicies, matrix, nrow=20, ncol=4)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top