在具有输入组合的循环中使用具有2个输入的功能来创建数据帧

时间:2017-03-20 19:34:20

标签: r function for-loop

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

# 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,delta和information,其中theta和delta都是函数中使用的序列的值,而signal是函数的输出对于theta和delta的每个组合。

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

#nested for loop

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

2 个答案:

答案 0 :(得分:2)

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

outer(thetas,deltas,info.theta)

答案 1 :(得分:1)

对原始功能略有改动:

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
相关问题