rlistappendspike

How to append first and last element in each vector (of a different length) of a list in R, without making the code slow?


I am working on simulating nonhomogeneous processes to understand the neural behavior better. My code works in a way that I have, say 20 trials lasting 2 seconds each (each trial representing a spike train). Then the list SpikeTimes gives me a list of 20 vectors where each vector corresponds to the time stamps of where the spikes occurred in that particular trial. [Eg.SpikeTimes[1] which looks like this, 0.002250802 0.053934034...1.971574170 2.023090384 means that in the first Spike Train, spikes occurred at 0.002250802, 0.053934034 and so on. I don't know why it also brings up a time stamps beyond my time limit of 2 seconds, but I will work on that later]. My code looks like this--

nTrials=20
t_max=2.0000000


LambdaInv<- function(x){ifelse( x< 15, x/30,
                    ifelse(x >= 15 & x < 38, ((x-15)/46)+0.5,
                           ifelse(x >= 38 & x <53, ((x-38)/30)+1.0,
                                  ifelse(x >= 53 & x< 67.4, ((x-53)/72)+1.5, 
                                         ((x-67.4)/30)+1.7))))}
   
 t = 0 
 s = 0
 X = numeric(0)


 NonHomoSpikes <- function(t_max){
  while(t <= t_max){
    u <- runif(1)
    s <- s-log(u)
    t <- LambdaInv(s)
    X <- c(X,t)
       }
    return(X)
   }


SpikeTimes <- lapply(1:nTrials, function(x) NonHomoSpikes(2))

My problem is that, for each of the vector in the list SpikeTimes; which gives time stamps of spikes, I also want to include the beginning (that is 0) and the end (that is 2) of the spike train. So I want to append this list to have each vector include the first entry as 0 and the last entry as 2.

My SpikeTimes[1] would then look like 0 0.002250802 0.053934034...1.971574170 2 and other SpikeTimes[i] would look similar. I tried SpikeTimes <- c(0, SpikeTimes) for entering 0 in the beginning but it only made the list have 21 vectors instead of 20 with the vector 0 as the first element (I mean I get why that happened). How can I do it in a way that doesn't make my code slow? I am newbie in R and reading up on the internet hasn't help with this particular problem. I would appreciate any sort of input.


Solution

  • Solution: change NonHomoSpikes return statement to return(c(0, X, 2)).

    To 'manually' stop if t < 2 (as described in comments):

    NonHomoSpikes <- function(t_max){
      while(t <= t_max){
        u <- runif(1)
        s <- s-log(u)
        t <- LambdaInv(s)
        if(t > 2) break
        X <- c(X,t)
           }
        return(c(0,X,0))
       }