Question

I have a list of vectors and for each vector in the list I would like to extract the elements and use their values as arguments in a function. Here is the general idea of what I have come up with so far.

#Function to convert parametric values (stored in vector) to multivariate normal random data

ParamsToDat = function(X){
  vec = X
  MultN = rmvnorm(vec[4],c(vec[2],vec[3],matrix(c(vec[5],vec[1],vec[1],vec[6]), 2, 2, byrow = FALSE)))
  return(MultN)
}



# Create list of randomly generated matrices based on parameters

GenData = function(MeanPre,MeanPost,Cov,SampSize,SampSD,IndVar1,IndVar2){

  #Use GenParams function to generate list of vectors each of length 6
  Params = GenParams(MeanPre,MeanPost,Cov,SampSize,SampSD,IndVar1,IndVar2)

  #Use lapply function to create list of matrices of multivariate normal data
  MatList = lapply(X = Params, FUN = ParamsToDat)

  MultN = list(Matlist = Matlist, Params = Params)

  return(MultN)

}

Each element in the list Params is a vector of length 6. I would like the function ParamsToDat to extract the elements of a vector in the list and use them as arguments to generate a matrix of multivariate normal data. This matrix will replace the vector from which the values were derived.

I am obviously messing something up with my ParamsToDat function or the lapply function or both since it is not working. Any Ideas how I could accomplish this?

Was it helpful?

Solution

The main problem is that R is case sensitive, so the line

MultN = list(Matlist = Matlist, Params = Params)

should be

MultN = list(Matlist = MatList, Params = Params)

Notice that I changed Matlist to MatList.

I think a misplaced ) will still give you a problem that won't cause an error in the line

MultN = rmvnorm(vec[4],c(vec[2],vec[3],matrix(c(vec[5],vec[1],vec[1],vec[6]), 2, 2, byrow = FALSE)))

I'm guessing that you really want

MultN = rmvnorm(vec[4],c(vec[2],vec[3]),matrix(c(vec[5],vec[1],vec[1],vec[6]), 2, 2, byrow = FALSE))

In your code, you've spent the time to make a matrix that looks like it's supposed to be the variance-covariance matrix in the call to rmvnorm(), but the misplaced ) will turn that back into a vector, so while you may be expecting to have two means and an interesting variance-covariance matrix, you end up with six means and a variance-covariance matrix of diag(6).

Hope this helps. Good luck!

OTHER TIPS

Here is my solution. Thanks for the response.

### This function accepts a vector of length six and converts it to bivariate normal data ###
VecToNorm = function(vec){
  BivNorm = abs(round(rmvnorm(vec[4],c(vec[2],vec[3]),matrix(c(vec[5],vec[1],vec[1],vec[6]), 2, 2, byrow = FALSE))))
  return(BivNorm)
}


### Function to convert parametric values from list of vectors to multivariate normal random data ###
ParamsToDat2 = function(Params){
  Data = lapply(Params, FUN = VecToNorm)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top