0

I have a function that returns a sample of Brownian motion as a result which is in form of data.frame odd columns are the times of each sample and even columns are the data corresponding to the previous time column. I also have a function that graphs the result of a single motion(two consecutive columns) I want to add all the graphs to one general graph using the following function

Plot_a_Sample_of_Brownian_Motions <- function(Mdata, SampleSize){
  Mdata <- as.matrix(Mdata)
  sum <- 0
  g <- Plot_a_brownian_motion(Mdata[,c(1,2)])
  for (i in 2:SampleSize) {
    x1 <- (2*i) -1
    y1 <- (2*i)
    g <- g + geom_line(aes(x = Mdata[,x1], y = Mdata[,y1]))
  }
  g
}

but when I run the code for example for 5 samples the results consist of two of the motions at the time. like the following result plot

and not all together, I'd appreciate it if you could help me with this problem.

I was expecting all of the motions on the same plot.

stefan
  • 90,330
  • 6
  • 25
  • 51
Llama97
  • 5
  • 4
  • 1
    You are running in the pitfalls of lazy evaluation. To prevent that the ggplot2 way of adding multiple layers would be to use a list, i.e. use lapply instead of a for loop or vene better reshape your data and use just one geom_line. See e.g. [R loop not changing variable](https://stackoverflow.com/a/75524974/12993861) for an example of both approaches. – stefan Mar 03 '23 at 16:13
  • I also recommend reshaping your data and using a single `geom_line` call, and just not bothering with the for loop. – Axeman Mar 03 '23 at 16:18
  • thanks very much I used lapply and it worked. – Llama97 Mar 03 '23 at 16:34

0 Answers0