【问题标题】:Errors when trying to create and use a random permutation test function in R尝试在 R 中创建和使用随机排列测试函数时出错
【发布时间】:2016-07-06 17:37:02
【问题描述】:

我正在尝试在 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)

我不确定错误代码是什么意思,也不确定如何解决问题以使函数运行。我将非常感谢您能提供的任何帮助,说明我在哪里出错了!

【问题讨论】:

    标签: r function error-code


    【解决方案1】:

    所以它似乎对我有用,只需进行一些更改。 首先,我假设饮料和蚊子的长度应该相同,但在您的问题中并非如此。

    > 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)
    }
    

    【讨论】:

    • 谢谢!我只是想学习这种编码,非常感谢您的帮助!
    猜你喜欢
    • 2019-09-12
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多