简体   繁体   中英

How to create a plot from the output of a function in R

I have a function that calculates the log-likelihood for a vector of expression levels in genes (x); eg -0.465, 0.111, -0.437. Sigma value calculated is 0.4717 and a = 0.8861.

    loglike <- function(x,theta,sigma,a) {
      sum(log(theta/(2*a)*(x<a)*(x>-a) + (1- 
      theta)*dnorm(x,mean=0.0,sd=sigma)))
    }

I want to input a vector of possible values for theta into the function and plot the result of the function with each value for theta. So I thought a for loop to rotate over all the values of theta in the function to create a list of values from the outputs of the loglike function. Then create a plot of theta against the loglike result.

   theta <- seq(0,1,0.01)  

   result_ <- c()
   for (i in 1:length(theta)) {
      result <- loglike(x,i,sigma,a)
      result_[i] <- result[i]
   }

But this just gives me warning messages:

   Warning messages:
   1: In log(theta/(2 * a) * (x < a) * (x > -a) + (1 - theta) * 
   dnorm(x,  :
     NaNs produced

I know that the function works because when I use the function one at a time it returns values, such as

    loglike(x,0,sigma,a)
    > -333.454234

I'm not hugely confident in R as a language, so would really appreciate any help.

Thank you for adding the values of x, a and sigma: these allowed me to find your bug.

In this loop here:

  for (i in 1:length(theta)) {
      result <- loglike(x,i,sigma,a)
      result_[i] <- result[i]
   }

you are inputting i as the value of theta to the loglike function. Remember i is the index number of the loop that goes from 1 to 101, but you want the theta value at each cycle of the loop, so it should be theta[i] .

Also, because your loglike function only ever returns a single number, you are storing a single number to result but then trying to store result[i] to result_[i] . When the loop goes past i = 1, you are trying to move a non-existent number.

Here's a full working example:

loglike <- function(x, theta, sigma, a)
{
  sum(log((theta / (2*a)) * (x < a) * (x > -a) +
          (1 - theta) * dnorm(x, mean = 0.0, sd = sigma)))
}

x       <-  0.111
sigma   <-  0.4717
a       <-  0.8861
theta   <- seq(0, 1, 0.01)
result  <- numeric()

for (i in 1:length(theta)) result[i] <- loglike(x, theta[i], sigma, a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM