将函数应用于R中的向量列表

时间:2019-03-31 12:39:07

标签: r function vector

我有一个保存在“ survieF.csv”中的值的列表,如下所示: 第一行包含以年(1年,3年,5年和10年)表示的时间,第二行包含第一列中变量的名称以及其余4列中的生存率。

         1      3    5    10
 var1   0.9   0.85  0.83  0.81
 var2   0.87  0.86  0.84  0.81
 var3   0.79  0.77  0.75  0.72

survieF<-read.csv("SurvieF.csv", sep=";", dec=".", header=TRUE)

例如,在下面给出的代码中,

S<-survieF[3,2:5]
x<-c(1,3,5,10)

功能:

f <- function(ab){
a <- ab[1]
b <- ab[2]
return(sum((exp(a*x**b)-S)**2))
} 

使用nlm函数查找使我的总和最小化的参数:

minim <- nlm(f,p=c(1,0))

ab <- minim$estimate

a_opt <- ab[1]
b_opt <- ab[2]

使用最佳参数获取值:

prediction_exp <- function(x){
return(exp(a_opt*x**b_opt))}

然后我使用这些参数估算1至20年的生存率。

survieFcan<-prediction_exp(1:20)

但是,我希望能够在数据框“ survieF”的每一行上自动运行代码,然后在excel上导出从1年到20年的所有估计值。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

$tickets = collect(json_decode($response->getBody()->getContents(), true)); $tickets = $tickets->filter(function($ticket) { return $ticket['createdAt'] >= now(); }); 的每一行上运行$tickets = array_filter($tickets, function($ticket) { return $ticket['createdAt'] > now(); }); 的技巧是将nlm()内联函数用作其第三个参数,以接收合适的参数并调用{ {1}}。

以下示例对此进行了说明:

survieF

其输出是:

apply()

然后,您可以采用类似的策略来获取每个变量nlm()#--- 1) Read the data # Note: # - the use of row.names=1 so that 'var1', 'var2', ... are stored as row names # instead of being read as data values. # - the computation of the independent variable 'years' # (used as x in the function to optimize) from the column names read # (so that we do not hardcode its values, but read them from the input data instead) survieF <- read.csv("SurvieF.csv", sep=";", dec=".", header=TRUE), row.names=1) years <- as.numeric( substring( names(survieF), 2 ) ) #--- 2) Define the function to optimize that also defines the model to fit # Note that two parameters were added, 'S' and 'x', so that: # - we can pass the value of S as every row of survieF via apply() below # - the function is fully self-contained (in the previous version, # one needs to "magically" know that object x needs to be defined # already in order for the function to work properly) f <- function(ab,S,x){ a <- ab[1] b <- ab[2] return(sum((exp(a*x**b)-S)**2)) } #--- 3) Obtain the estimated parameters for each row of survieF opt_params <- apply(survieF, 1, function(S,years) { nlm(f,p=c(1,0),S,years)$estimate }, years) var1 var2 var3 [1,] -39.68255 -39.73691 -41.63971 [2,] -51.56907 -51.42185 -53.87351 的1年至20年的预测值。