1

I need to plot in R a function of the log likelihood. I have a fixed n, multiple values for k and arbitrary pi between 0 and 1. I tried this code but the result is not what i want:

n<-10
k<-c(8,8,5,4,6)
pi = seq(0,1,length=100)
l = function(pi){k*log(pi) + (n-k) * log(1-pi)}
plot(x=pi,y=l(pi),ylab="l(pi)",xlab="q",type="l",ylim=c(-10,0))

the plot is far from a normal curve

please help

0

2 Answers 2

1

You might be looking for curve. Just define your function in first curve argument, using x as variable, and the first k[1]. In a second step loop the same over the remaining k[2:5] using add=TRUE argument.

n <- 10
k <- c(7,8,5,4,6)

curve(k[1]*log(x) + (n-k[1]) * log(1-x), ylim=c(-40, 0))
invisible(sapply(seq(k[-1]) + 1, function(i)
  curve(k[i]*log(x) + (n-k[i]) * log(1-x), col=i, add=TRUE)))
legend("bottomright", legend=k, lty=1, col=1:5, title="k", horiz=T, cex=.8)

enter image description here

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

Comments

0

The problem lies in how R handles your 'multiple values of k'.

Because k is a vector of length 5, and pi is a vector of length 100, k is 'recycled', meaning that R pairs each pi with a value of k in turn:

pi: 0.01 0.02 0.03 0.04 0.05           0.06 0.07 0.08
k:    8    8    5    4    6 [back to:]   8    8    5 ...

Instead, you want to plot each k separately:

pi = seq(0, 1, length = 100)
l = function(pi, k) k * log(pi) + (n-k) * log(1-pi)
plot(x = pi, y = l(pi, 8), ylab="l(pi)", xlab = "q",
     ylim = c(-10, 0))
lines(x = pi, y = l(pi, 5), col = 'red')
lines(x = pi, y = l(pi, 4), col = 'blue')
lines(x = pi, y = l(pi, 6), col = 'orange')

plot

2 Comments

would making pi of length 5 do any better?
Did you try this in R and see what happened? Your pi values correspond to points on the x axis at which the function l(pi) is evaluated. With five entries in pi, you'd end up with just five points.

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.