如果有人能帮助我,试图找出为什么我的功能不工作。尽管定义了"b"作为函数的输入和"upper"在函数中,我收到以下错误消息:
while (b <)
下面是我的函数的代码和我试图使用的输入:
## Require package "DescTools" for CorCI() function and install if not installed
if (!require('DescTools')) install.packages('DescTools'); library('DescTools')
my.function <- function(a, b, c = .8, d = .9){
n <- 2 ## Set counter at 2
upper <- 1 ## Set initial upper value to 1 so it will be greater than b
while (b < upper) {
n <- n + 1
CI1 <- CorCI(rho = a, n = n, conf.level = d, alternative = "two.sided")
CI2 <- CorCI(rho = unname(CI1[3]), n = n, conf.level = c, alternative = "less")
upper <- unname(CI2[3])
}
print(n)
}
my.function(a = -.5, b = -.3)
我已经尝试了一堆不同的解决方案,似乎没有一个工作。我用repeat和break循环替换了while循环,但这并没有帮助。奇怪的是,我有另一个函数,它非常相似,但只是切换了一些东西的方向(输入也不同,因为函数服务的任务略有不同),它工作得很好。下面是起作用的函数:
## Require package "DescTools" for CorCI() function and install if not installed
if (!require('DescTools')) install.packages('DescTools'); library('DescTools')
my.function2 <- function(a, b, c = .8, d = .9){
n <- 2 ## start n counter at 2
lower <- -1 ## Set initial lower value to -1 so it will be less than b
while (b > lower) {
n <- n + 1
CI1 <- CorCI(rho = a, n = n, conf.level = d, alternative = "two.sided")
CI2 <- CorCI(rho = unname(CI1[2]), n = n, conf.level = c, alternative = "greater")
lower <- unname(CI2[2])
}
print(n)
}
my.function2(a = .5, b = .3)
这两个函数看起来应该是等价的,所以我不知道为什么一个可以工作而另一个不能。你能提供的任何见解都会非常有帮助!谢谢!
亚当
解决方案:根据Mohan Govindasamy的一个有用的评论,他指出unname(CI2[3])返回一个NaN,我仔细研究了CorCI代码,并意识到当N被设置为3(初始2 + 1)时,CorCI返回一个NaN作为置信区间,因为没有足够的值。因此,我只是将初始计数器改为n <- 5,而不是n <- 2,这就解决了问题!谢谢,莫汉!
工作代码:
## Require package "DescTools" for CorCI() function and install if not installed
if (!require('DescTools')) install.packages('DescTools'); library('DescTools')
my.function <- function(a, b, c = .8, d = .9){
n <- 5 ## Set counter at 5 instead of 2
upper <- 1 ## Set initial upper value to 1 so it will be greater than b
while (b < upper) {
n <- n + 1
CI1 <- CorCI(rho = a, n = n, conf.level = d, alternative = "two.sided")
CI2 <- CorCI(rho = unname(CI1[3]), n = n, conf.level = c, alternative = "less")
upper <- unname(CI2[3])
}
print(n)
}
my.function(a = -.5, b = -.3)