1

I would like to get only one curve that is the "average" of all curves in order to get the "average trend". In my specific case, it is to average simulations I made.

Using this tutorial (cf the code below) , I managed to get multiple curves like this :

enter image description here

Here is the code to get the plot above :

set.seed(06062023)
my_values = list(rnorm(10),rnorm(10),rnorm(10),rnorm(10),rnorm(10),
                      rnorm(10),rnorm(10),rnorm(10),rnorm(10),rnorm(10))

den<-lapply(my_values, density)
plot(den[[1]], ylim=c(0,0.8), xlim=c(-6,6),main='Densities altogether') 
for(i in 2:length(den)){        
  lines(den[[i]], col=i)        
}
1
  • 1
    I would suggest looking at this CrossValidated post: stats.stackexchange.com/questions/31689/… as it asks a similar question. Hint: look at the weights argument in the density function. Commented Jun 6, 2023 at 15:39

1 Answer 1

2

We can use approx to get esimates from the densities at a consisted grid and then take the average over those values. For example

z <- seq(-6, 6, length.out=100)
zavg <- rowMeans(sapply(den, function(d) approx(d$x, d$y, z, yleft=0, yright=0)$y))
lines(z, zavg, col="red", lwd=3)

This creates the think red line on the plot enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.