【问题标题】:Using a Function With 2 Inputs in a Loop With Combinations of Inputs to Create a Data Frame在循环中使用具有 2 个输入的函数和输入组合来创建数据框
【发布时间】:2017-03-20 19:34:19
【问题描述】:

我创建了一个自定义函数来根据两个输入计算值。

# function
info.theta <- function(theta, delta) {
    P = 1/(1+exp(-1*(theta-delta)))
    Q = 1 -P
    1*P*Q
}

我想使用该函数来计算两个感兴趣序列的所有可能值组合的值。

# for each input of the function create sequences of values to explore
thetas <-  seq(-4, 4, by = .5)
deltas <- seq(-4, 4, by = .5)

我想最终得到一个数据框,其中有一列标记为 thetas、deltas 和 information,其中 theta 和 delta 都是函数中使用的序列的值,而 information 是函数的输出对于 theta 和 delta 的每个组合。

我不知道如何执行最后一点,因为这种级别的编码对我来说是新的。我的预感可能是嵌套的 for 循环。这显然是不正确的,但它已经尽可能接近开始了。我将如何以我描述的方式使用该函数来生成所需的数据框?

#nested for loop

y <- NULL
for(i in sequence) {
    for(j in deltas) {
    tmp <- info.theta(i, j)
    y <- rbind(y, tmp)  
    }
}
y

【问题讨论】:

  • 是的,一旦事情开始爆发,循环就不是很有趣了。如果您必须比较 n 的东西怎么办?

标签: r function for-loop


【解决方案1】:

您可以使用outer 获取值矩阵:

outer(thetas,deltas,info.theta)

【讨论】:

    【解决方案2】:

    对原来的功能稍作改动:

    info.theta <- function(theta, delta) {
      P = 1/(1+exp(-1*(theta-delta)))
      Q = 1 -P
      data.frame(theta=theta,delta=delta, information=1*P*Q)
    
    }
    

    因为 data.frames 更酷。

    现在:

    td_grid<-expand.grid(thetas, deltas)
    info.theta(td_grid[,1],td_grid[,2])
    

    结果:

        theta delta  information
    1    -4.0  -4.0 0.2500000000
    2    -3.5  -4.0 0.2350037122
    3    -3.0  -4.0 0.1966119332
    4    -2.5  -4.0 0.1491464521
    5    -2.0  -4.0 0.1049935854
    6    -1.5  -4.0 0.0701037165
    7    -1.0  -4.0 0.0451766597
    8    -0.5  -4.0 0.0284530239
    9     0.0  -4.0 0.0176627062
    10    0.5  -4.0 0.0108662297
    11    1.0  -4.0 0.0066480567
    

    【讨论】:

    • 完美。希望随着我编码的进步,我将学会更好地表达我的目标,并且能够在来这里之前更轻松地解决这些问题。如果我能更清楚地表达我的问题,“expand.grid”似乎是一个非常简单的解决方法。
    • 是的,我在上面添加了一条评论,但我会将其包含在此处。尽可能地努力避免循环。您可以使用apply() 函数组编写更简洁、有效和更快的代码。另外,如果你想变得更漂亮,你可能会在函数中包含expand.grid() 部分,这样它只需要两个向量并根据你的喜好输出一个 data.frame。
    猜你喜欢
    • 1970-01-01
    • 2013-08-28
    • 2021-01-14
    • 2022-01-19
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多