繁体   English   中英

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

[英]Using a Function With 2 Inputs in a Loop With Combinations of Inputs to Create a Data Frame

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

# 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。

我对如何执行最后一点一无所知,因为这种编码水平对我来说是新的。 我的预感也许是嵌套循环的。 这显然是不正确的,但是就我所知。 如何以我描述的方式使用该函数来生成所需的数据帧?

#nested for loop

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

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

outer(thetas,deltas,info.theta)

对原始功能进行了微小的更改:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM