Ana
Ana

Reputation: 11

Plotting a function in R with multiple values for variable

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

Upvotes: 1

Views: 763

Answers (2)

Martin Smith
Martin Smith

Reputation: 4077

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

Upvotes: 0

jay.sf
jay.sf

Reputation: 72813

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

Upvotes: 1

Related Questions