尝试在R中创建和使用随机排列测试函数时出错

时间:2016-03-20 04:26:03

标签: r function error-code

我正在尝试在RStudio中完成随机排列测试并继续得到以下两个错误: 错误:评估嵌套太深:无限递归/选项(表达式=)? 换行时出错:评估嵌套太深:无限递归/选项(表达式=)?

#create groups/data vectors
drinks = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
mosquito = c(27, 20, 21, 26, 27, 3, 24, 21, 20, 19, 23, 24, 28, 19, 24, 29, 18, 20, 17, 31, 20, 25, 28, 21, 27, 21, 22, 15, 12, 21, 19, 15, 22, 24, 19, 23, 13, 22, 20, 24, 18, 20)

#create function
rpermut = function(group, outcome, permutation){
diff = rep(NA, permutation)
for(i in 1:permutation){
outcome = sample(outcome)
diff[i] = mean(outcome[group==levels(group)[1]]) - mean(outcome[group==levels(group)[2]])}
diff
}

#adding values to function
mosrep = rpermut(group=drinks, outcome=mosquito, permutation=1000)

我不确定错误代码是什么意思,也不知道如何解决问题,以便运行该功能。如果我在这里遇到错误,我可以提供任何帮助,我将不胜感激!

1 个答案:

答案 0 :(得分:0)

所以它似乎对我有所改变。 首先,我假设饮料和蚊子的长度应该相同,而问题并非如此。

> length(drinks)
[1] 43
> length(mosquito)
[1] 42

其次,levels()对因子起作用,而那些对象饮料和蚊子是数字向量。

> class(drinks)
[1] "numeric"
> class(mosquito)
[1] "numeric"

因此,在我的机器上运行此功能,我必须调整功能:

rpermut = function(group, outcome, permutation){
    diff = c()
    group = as.factor(group)
    for(i in 1:permutation){
        outcome = sample(outcome)
        diff[i] = mean(outcome[group==levels(group)[1]]) - mean(outcome[group==levels(group)[2]])
    }
    return(diff)
}

这只是将组更改为as.factor()

的因子

我还将diff = rep(NA, permutation)更改为只创建空向量的diff = c()。无需为所有值分配NA,因为您可以使用diff[i]以相同的方式填充条目。

因此,向量需要长度相同,然后这应该可以工作,也可以简单地添加一个检查。

if(length(group) != length(outcome)){
        stop("input vector lengths does not match!")
    }

所有在一起:

rpermut = function(group, outcome, permutation){
    if(length(group) != length(outcome)){
        stop("input vector lengths does not match!")
    }
    diff = c()
    group = as.factor(group)
    for(i in 1:permutation){
        outcome = sample(outcome)
        diff[i] = mean(outcome[group==levels(group)[1]]) - mean(outcome[group==levels(group)[2]])
    }
    return(diff)
}