【问题标题】:Applying functions to a list of vectors in R将函数应用于 R 中的向量列表
【发布时间】:2019-03-31 12:39:07
【问题描述】:

我有一个保存在“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 年估计的所有值。我怎样才能做到这一点?

【问题讨论】:

  • 几个 cmets:(i) 如果您的 CSV 文件包含您在顶部显示的数据(即 2 行以分号分隔的值,其中值位于第一行,并且值在第二行),您不会将 values 读入survieF,因为默认情况下read.csv() 中的header=TRUE 和值将被读取为列names我>; (ii) 创建S 的循环的目的是什么? S 的值分配给 n 行,因为它在每次迭代时都会被覆盖...
  • 你好。我已经编辑了我的问题。我实际上想在我的数据帧的每一行上运行代码,因此在 S.. 上循环。

标签: r function vector


【解决方案1】:

survieF 的每一行上运行nlm() 的技巧是将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

然后,您可以按照类似的策略来获取每个变量var1var2var3 在第 1 年到第 20 年的预测值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    相关资源
    最近更新 更多