0

I'm trying to plot a simulation of a differential equation versus its exact analytical solution, but keep getting "Error in FUN(X[[i]], ...) : object 'value' not found", even though it is declared just the line before! It seems like I have made a silly mistake in some place, but I cannot find it at all. Plus, it doesnt recognized the labels I specified, giving a "unexpected symbol error". Thanks in advance,

require(ggplot2)
N<-500
T<-3
dt<-T/N
X <-c()
X[1] <-4

B<-numeric(N+1)
tt<-seq(0,T,length=N+1)

for(t in seq(2,N+1)){
  B[t] <- B[t-1]+rnorm(1)*sqrt(dt)
}

for(i in seq(2,N+1)){
  X[i] <- X[i-1]+2*B[i-1]*(B[i]-B[i-1])+dt
}



  S <- as.data.frame(rep(X[1],501) + B^2)
  names(S) <- (c('value','t','Solutions') labels=c("Simulation", "Exact Solution") )
  ggplot(data = S, aes(x = t, y = value, colour = variable)) + geom_line()

P.E:Sorry if this is a way to stupid question, I'm a noob using R, but I'm force to use it for work realted things.

  • The line `names(S) <- ...` is not valid R code. Double-check that `S` has correct column names. In fact, the line `S <- as.data.frame(rep(X[1], 501) + B^2)` also looks odd. What dimensions is `S` supposed to have? – Maurits Evers Nov 28 '18 at 21:31
  • I'm having a hard time figuring out what the intended structure of X and S were supposed to be. X is just a numeric vector, so S is just a one column data frame, so I'm not sure where the other columns are supposed to come from. – joran Nov 28 '18 at 21:40
  • It's supposed to be a 501x2 dataframe, containing the X (the simulated solution) and S (the exact solution) –  Nov 28 '18 at 21:47
  • So maybe what you wanted was `data.frame(sim_solution = X,exact_solution = S)` and then `gather` that data frame and then use `ggplot`...? – joran Nov 28 '18 at 21:50
  • I tried like you said, but still gives the error of value not specified. –  Nov 28 '18 at 22:05
  • Can you edit the code with what you tried? This isn't really a ggplot issue as much as it is getting your data frame formatted correctly. – r_alanb Nov 28 '18 at 23:02

1 Answers1

1

Along the lines of @joran's comment, this should work. I'm not sure I'm interpreting your intentions correctly for the S <- as.data.frame(rep(X[1],501) + B^2) line in your code, but hopefully this points you in the right direction to resolve your question.

set.seed(42)
# <- all your code before the bottom section

library(tidyverse)
S <- data.frame(t = tt, simulated = X, exact = B^2 + X[1]) %>%
  gather(variable, value, -t)
ggplot(data = S, aes(x = t, y = value, colour = variable)) + geom_line()

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Ok, thank you! I see know where I was wrong. Didnt even know the tidyverse library, you opened a new frontier for me! –  Nov 29 '18 at 09:30