長期讀者,第一次海報。我沒有發現任何關于我當前問題的先前問題。我想創建多個線性函式,以后可以將其應用于變數。我有一個斜率資料框:df_slopes 和一個常量資料框:df_constants。虛擬資料:
df_slope <- data.frame(var1 = c(1, 2, 3,4,5), var2 = c(2,3,4,5,6), var3 = c(-1, 1, 0, -10, 1))
df_constant<- data.frame(var1 = c(3, 4, 6,7,9), var2 = c(2,3,4,5,6), var3 = c(-1, 7, 8, 0, -1))
我想建構式,例如
myfunc <- function(slope, constant, trvalue){
result <- trvalue*slope constant
return(result)}
其中斜率和常數值是
slope<- df_slope[i,j]
constant<- df_constant[i,j]
我嘗試了很多方法,例如像這樣,使用 for 回圈創建函式的資料框
myfunc_all<-data.frame()
for(i in 1:5){
for(j in 1:3){
myfunc_all[i,j]<-function (x){ x*df_slope[i,j] df_constant[i,j] }
full_func[[i]][j]<- func_full
}
}
沒有成功。斜率常數值成對出現,例如 df_slope[i,j] 與 df_constant[i,j] 配對。所需的最終結果將是某種資料框,我可以通過給它坐標來呼叫函式,例如: myfunc_all[i,j} 但任何形式都可以。例如
myfunc_all[2,1]
在我們的情況下將是
function (x){ x*2 4]
我可以將其應用于不同的 x 值。我希望我的問題很清楚。
uj5u.com熱心網友回復:
df_slope <- data.frame(var1 = c(1, 2, 3,4,5), var2 = c(2,3,4,5,6), var3 = c(-1, 1, 0, -10, 1))
df_constant<- data.frame(var1 = c(3, 4, 6,7,9), var2 = c(2,3,4,5,6), var3 = c(-1, 7, 8, 0, -1))
functions = vector(mode = "list", length = nrow(df_slope))
for (i in 1:nrow(df_slope)) {
functions[[i]] = function(i,x) { df_slope[i]*x df_constant[i]}
}
f = function(i, x) {
functions[[i]](i, x)
}
f(1, 1:10)
f(3, 5:10)
uj5u.com熱心網友回復:
因此,當您使用 for 回圈構建函式時,延遲評估和變數范圍會出現一個小問題(有關更多資訊,請參見此處)。使用類似的東西mapply會為你創建閉包更安全。嘗試
myfunc_all <- with(expand.grid(1:5, 1:3), mapply(function(i, j) {
function(x) {
x*df_slope[i,j] df_constant[i,j]
}
},Var1, Var2))
dim(myfunc_all) <- c(5,3)
這將創建一個類似物件的陣列。唯一的區別是您需要使用雙括號來提取函式。例如
myfunc_all[[2,1]](0)
# [1] 4
myfunc_all[[5,3]](0)
# [1] -1
或者,您可以選擇撰寫一個回傳函式的函式。那看起來像
myfunc_all <- (function(slopes, constants) {
function(i, j)
function(x) x*slopes[i,j] constants[i,j]
})(df_slope, df_constant)
然后,而不是使用括號,您使用括號呼叫該函式。
myfunc_all(2,1)(0)
# [1] 4
myfunc_all(5,3)(0)
# [1] -1
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342954.html
