2

How can I write a function to check cases(x,y) by the two tests:

One

if y==rank(y) 

Two

xranks <- rank(x)
yranks <- rank(y)
meanx <- mean(xranks)
meany <- mean(yranks)
covariance.term <- cov(xranks-meanx,y-meany)
sd.x <- sd(xranks)
sd.y <- sd(yranks)
if -1<= covariance.term/(sd.x*sd.y) <=1

and should return TRUE if both tests are passed, or FALSE, with warnings about which tests failed.

4

2 回答 2

1

以下应该做你想要的,但由于你没有提供测试用例,我不确定它是否有效。

check.xy <- function(x,y) {
    xranks <- rank(x)
    yranks <- rank(y)
    meanx <- mean(xranks)
    meany <- mean(yranks)
    covariance.term <- cov(xranks-meanx,y-meany)
    sd.x <- sd(xranks)
    sd.y <- sd(yranks)
    testA <- all(y == rank(y))
    testB <- all(-1 <= covariance.term/(sd.x*sd.y) & covariance.term/(sd.x*sd.y) <=1)
    if (testA & testB) return(TRUE)
    else if (testA) warning("test two failed")
    else if (testB) warning("test one failed")
    else warning("tests one and two failed")
    FALSE
}
于 2012-12-04T16:29:37.497 回答
0

我认为在单个函数中定义每个测试,尤其是我们想要关于哪些测试失败的警告。

这两个测试共享相同的环境,这就是我将它们定义为嵌套函数的原因。

multitest <- function(x,y){
 test.covariance <- function(){
    xranks <- rank(x)
    yranks <- rank(y)
    meanx <- mean(xranks)
    meany <- mean(yranks)
    covariance.term <- cov(xranks-meanx,y-meany)
    sd.x <- sd(xranks)
    sd.y <- sd(yranks)
    cov.norm  <- covariance.term/(sd.x*sd.y) 
    res <- cov.norm  > -1 && cov.norm < 1
    if(is.na(res) || res > 0) warning('test covariance range failed',.call = FALSE)
    res
}
 test.rank <- function(){
   res <- all(y==rank(y))
   if(!res) warning('test rank failed')
   res
 }
 res <- test.covariance() && test.rank()
 !is.na(res)
}

一些测试:

成功

x <- 1:10
y <- 1:10
multitest(x,y)
[1] TRUE

失败等级

x <- rnorm(10)
y <- rnorm(10)
multitest(x,y)
[1] FALSE
Warning message:
In test.rank() : test rank failed

失效协方差

x <- rep(10,10)
y <- 1:10
multitest(x,y)
[1] FALSE
Warning message:
In test.covariance() : test covariance range failed
于 2012-12-04T18:18:57.140 回答