使用函数参数的函数内的For循环

时间:2019-11-17 21:47:40

标签: r function for-loop

我正在对超过400万个观察值的数据集进行回归分析。我正在尝试进行敏感性分析,以了解我的回归系数对不同样本量的敏感性。我要:

  • 随机抽取n个数据点
  • 对样本进行回归
  • 提取系数

我想重复上述步骤400次以创建系数分布并绘制均值和置信区间。我创建了两个函数来执行此操作。第一个是coef_sampler,对数据样本进行回归并返回系数:

Private Sub CommandButton1_Click()

    Dim i as long, b As Long, shtTC as worksheet, shtArch as worksheet

    Set shtTC = Worksheets("TC")
    Set shtArch  = Worksheets("Archive")

    'find the first empty row 
    b = shtArch.Cells(Rows.Count, 2).End(xlUp).Row + 1 'pick a column which will always be populated              

    For i = 2 To shtTC.Cells(Rows.Count, 2).End(xlUp).Row      
        If shtTC.Cells(i, 28).Value <> "" Then
            'cut the row
            shtTc.Cells(i, 1).Resize(1, 28).Cut shtArch.Cells(b, 1)
            b = b + 1
        End If
    Next

    Application.CutCopyMode = False

    shtTC.Cells(1, 1).Select

End Sub

第二个函数my_function针对不同的样本量将这个过程复制400次,生成不同样本量的系数向量。然后,使用Rmisc中的CI()函数计算每个向量的平均值以及上下限:

coef_sampler <- function(data,n){
      model <- lm(y ~ x, data = data[sample(nrow(data), n),])
      return(model[["coefficients"]][[1]])
  }

当我只使用所需的重复次数和一系列样本大小的值运行for循环时,它工作正常。当我使用上述值调用my_function()时,它根本不起作用。没有生成均值和置信区间的数据框。请注意,我在my_function中调用了my_function <- function(data, n, nrep, to, by){ for (j in seq.int(n, to, by)){ plist <- data.frame(pval = replicate(nrep, coef_sampler(data,j))) if(!exists("ci_mat")) { ci_mat <- data.frame(CI(plist[,1])) } else { ci_mat <- cbind(ci_mat, data.frame(CI(plist[,1]))) } } } 函数,这可能引起问题吗?还是使用for循环使用导致问题的函数参数。

希望我的问题有道理,所有帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

问题是您的函数没有返回填充的ci_mat。此变量仅存在于函数环境中,并在函数运行后销毁:

df <- data.frame(x = 1:100, y = 4*(1:100) + 5 + rnorm(100,5,10))

coef_sampler <- function(data,n){
  model <- lm(y ~ x, data = data[sample(nrow(data),n),])
  return(model[["coefficients"]][[1]])
}

my_function <- function(data,n,nrep,to,by){

  for (j in seq.int(n,to,by)){
    plist <- data.frame(pval = replicate(nrep,coef_sampler(data,j)))

    if(!exists("ci_mat")){
      ci_mat <- data.frame(Rmisc::CI(plist[,1]))
    }else{
      ci_mat <- cbind(ci_mat, data.frame(Rmisc::CI(plist[,1])))
    }
  }
  ci_mat
}    

# sample call
my_function(df, 5, 10, 100,1)

使函数返回ci_mat

答案 1 :(得分:1)

只需在函数末尾添加一个return

library(Rmisc)

my_data <- tibble(x = 1:5,
                  y = rnorm(5))

coef_sampler <- function(data,n){
  model <- lm(y ~ x, data = data[sample(nrow(data),n),])
  return(model[["coefficients"]][[1]])
}

my_function <- function(data,n,nrep,to,by){
  for (j in seq.int(n,to,by)){
    plist <- data.frame(pval = replicate(nrep,coef_sampler(data,j)))

    if(!exists("ci_mat")){
      ci_mat <- data.frame(CI(plist[,1]))
    } else {
      ci_mat <- cbind(ci_mat, data.frame(CI(plist[,1])))
    }
  }
  return(ci_mat)
}

my_function(my_data, 1, 2, 5, 1)