[英]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);我有一个函数可以计算基因 (x) 中表达水平向量的对数似然; eg -0.465, 0.111, -0.437.
例如 -0.465、0.111、-0.437。 Sigma value calculated is 0.4717 and a = 0.8861.
计算的西格玛值为 0.4717,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.我想将 theta 的可能值向量输入到函数中,并用每个 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.
所以我想到了一个 for 循环来旋转函数中 theta 的所有值,以从 loglike 函数的输出创建一个值列表。 Then create a plot of theta against the loglike result.
然后根据对数结果创建一个 theta 图。
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.我对 R 作为一种语言不是很有信心,所以非常感谢任何帮助。
Thank you for adding the values of x, a and sigma: these allowed me to find your bug.感谢您添加 x、a 和 sigma 的值:这些使我能够找到您的错误。
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.您将
i
作为 theta 的值输入到 loglike 函数中。 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]
.请记住,
i
是从 1 到 101 的循环的索引号,但是您需要循环每个循环的 theta 值,因此它应该是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]
.此外,因为您的
loglike
函数只返回一个数字,所以您将一个数字存储到result
,然后尝试将result[i]
存储到result_[i]
。 When the loop goes past i = 1, you are trying to move a non-existent number.当循环超过 i = 1 时,您正在尝试移动一个不存在的数字。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.