如果有人能帮我弄清楚为什么我的函数不工作,我会很高兴的。尽管定义了"b“作为函数的输入,并在函数中定义了”am“,但我还是收到了以下错误消息:
“while中出错(b <上部){:需要TRUE/FALSE的位置缺少值”
下面是我的函数和我尝试使用的输入的代码:
## 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)这两个函数看起来应该是等价的,所以我不知道为什么一个可以工作,而另一个不能。你能提供的任何见解都将是非常有帮助的!谢谢!
-Adam
发布于 2021-02-17 01:32:48
解决方案:基于Mohan Govindasamy的一条有用的评论,他指出unname(CI23)返回一个NaN,我仔细研究了Cor CI代码,并意识到当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)https://stackoverflow.com/questions/66219423
复制相似问题