私は別の関数(これをBと呼ぶ)(これらの関数を両方とも定義した)内で関数を使用しようとしています。これを行うために、私はB関数の始めにAの引数のいくつかを定義してから、do.callを使ってAを呼び出しました。しかし、関数Aは、定義されているにもかかわらず、それらの引数を認識していません。どうしたの?Do.callがRのユーザ定義関数のために欠落した引数を返す
コンテキスト:シンプルなシステムのシミュレーションを実行しようとしています。これを行うために、私は問題をさまざまなサブ機能に分割しています:1つは(genpar)シミュレーション用のランダムパラメータを生成し、もう1つは(indeffbasic)パラメータ値から可変値にマップします。次に、これら2つの関数をindeffという新しい関数で結合します。この最後のステップで、エラーが発生します。私は検索しましたが、解決策は見つかりません。答えが明らかな場合は、私を許してください。ない関数呼び出し、do.call
への最初の引数は機能(または関数の名前)である必要があり、あなたのラインで
#First we set up the data structure.
#In this simple model we have N variables, and each variable has a value at each time period.
#There are T time periods.
N <- 2
T <- 20
variables <- data.frame(matrix(0,T,N))
#I assign names to the variables, and check that I've given the right number of names
Names <- c("Movement", "AIpapers")
if(length(Names)==N){names(variables) <- Names} else {print("Error")}
#Now I assign the basic function that, given parameter values, runs a simulation over T time periods.
indeffbasic <- function(a0=5000, b0=100, a1, b1){
for (i in 1:T) {
variables[i, "Movement"] <- (if(i-1>0){a1* variables[i-1, "Movement"]}else{a0})
variables[i, "AIpapers"] <- (if(i-1>0){variables[i-1, "AIpapers"]}else{b0}) + (if(i-3>0){b1*variables[i-3, "Movement"]}else {0})
}
return(variables)
}
#This function works:
indeffbasic(a1=10, b1=2)
#Since I want a1 and b1 to be randomly generated each time,
#I define a function that randomly generates these values and returns them
genpar <- function() {
a1 <- rnorm(1, 1.1, 0.02)
b1 <- rnorm(1)
parameters <- c(a1, b1)
return(parameters)
}
#This function also seems to work
genpar()
#Now I define a function that randomly generates a1 and b1
#and then passes them to the indeffbasic function I defined above
#so each time I call this is like a run of the simulation.
indeff <- function(a0=5000, b0=100) {
parameters <- as.list(c(a0, b0, genpar()))
names(parameters) <- c("a0", "b0", "a1", "b1")
return(do.call(indeffbasic(), parameters))
}
#But this doesn't work: it returns "Error: argument "a1" is missing, with no default"
indeff()
'genpar'は(' c'のために)単一のベクトルを返しています。 'c(a1、b1)'を 'list(" a1 = a1、b1 "= b1)'に置き換えてa1とb1を抽出することで名前付きリストを返すことができます。 – lmo
ありがとうございました@lmo、あなたは正しいです。 – Oldmantax