# ggplot and for loop doesn't seem to work?

Does anybody know what's wrong? I get a warning message saying the amount of rows are 101 even though there only should be one argument, theta. I have tried the sum function instead of the for loop as well.

`````` #> code
p <- ggplot(data.frame(x=0), mapping=aes(x=x))
xsim <- rnorm(100,1,1)
logl <- function(theta){
a <- 0
(100/2)*log(2*pi*theta^2)+ for (j in 1:100){
a <- a+(xsim[j]-theta)^2/(2*theta^2)
}
}
}
p + stat_function(fun = logl) + xlim(-5,5)``````

The `for` function doesn't return a value. Is this what you want?

``````library(tidyverse)
#> code
p <- ggplot(data.frame(x=0), mapping=aes(x=x))
xsim <- rnorm(100,1,1)
theta <- .4 # for testing the function
logl <- function(theta){
a <- 0
for (j in 1:100){
a <- a+(xsim[j]-theta)^2/(2*theta^2)
}
return((100/2)*log(2*pi*theta^2)+a)
}
p + stat_function(fun = logl) + xlim(-5,5)
``````

Thanks. I know what the for loop does but it is probably the ggplot 'm a little confused about. I was looking for a replacement of the folllowing code using ggplot instead of lines combined with lapply.

``````    for (i in 1:5){
xsim <- rnorm(10,1,1)
logl <- function(theta){
(10/2)*log(2*pi*theta^2)+sum((xsim-theta)^2/(2*theta^2))
}
values <- lapply((theta_seq), logl)
lines(theta_seq, values, col=i)
}

``````

For ggplot you have to collect your data into a dataframe. I usually use a loop for this. Not sure exactly what you're trying to plot.

``````library(tidyverse)
theta_seq <- c(0.1, 0.2, 0.3)
ntheta <- length(theta_seq)
nsamples <- 5
df <- vector("list", ntheta*nsamples) # create an empty list for the results
for (i in 1:ntheta){
for (j in 1:nsamples){
xsim <- rnorm(100,1,1)
logl <- function(theta){
(10/2)*log(2*pi*theta^2)+sum((xsim-theta)^2/(2*theta^2))
}
df[[j+(i-1)*nsamples]] <- tibble(theta=theta_seq[i], sample=j, logl=logl(theta_seq[i]))
}
}
df <- bind_rows(df) # convert the list to a dataframe
ggplot(df) +
geom_line(aes(x=theta, y=logl, colour=as.factor(sample)))
``````
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.