0

I'm new in R and I have been trying to plot 4 exponential curves with different colors. I want to know how to do it with a for loop.

par(mfrow = c(2, 2))
colors<-rainbow(4)
parameters <- c(10, .25, 1, 6)
for(lambda in parameters){ 
curve(dexp(x, lambda), 0, 3, main = bquote(lambda ==.(lambda)),
font.main = 1, xlab = "x", ylab = "f(x)",col=colors[lambda])
}
1
  • similar to the answer below for(ii in seq_along(parameters)) {lambda <- parameters[ii]; curve(dexp(x, lambda), 0, 3, main = bquote(lambda ==.(lambda)), font.main = 1, xlab = "x", ylab = "f(x)",col=colors[ii])} Commented Feb 3, 2021 at 19:47

1 Answer 1

1

You were passing your parameter values to index your color object. Generally it's good practice to use 1:n integers in your for loops.

Try this:

for(lambda in seq_along(parameters)){ 
   curve(dexp(x, parameters[lambda]), 0, 3, main = bquote(parameters[lambda] ==.(parameters[lambda])),
         font.main = 1, xlab = "x", ylab = "f(x)",col=colors[lambda])
}
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.