【问题标题】:How to pass list to a function in R如何将列表传递给R中的函数
【发布时间】:2017-01-09 11:05:36
【问题描述】:

我想将线性回归的结果存储在截距和系数等列表中。我有以下代码

results  = list()
intercept = list()
coeff = list()

GetLM = function(dataframe,results,intercept,coeff){
     unq_clients = as.vector(unique(dataframe$clients))
     for(i in 1:length(unq_clients)){
         new_df=dataframe[dataframe$clients ==    unq_clients[i],]
         regression= lm(a ~ b,data = new_df )
         results[[i]] = coef(regression)
         intercept[i] = results[[i]][1]
         coeff[i]=results[[i]][2]
     }
}

但是当我调用该函数时,列表中没有存储任何内容。我做错了什么?

【问题讨论】:

  • 为什么您的函数中缺少 return() 语句。否则,对结果的任何添加都不会反映在功能范围之外。在函数末尾添加 return(list(results, intercept, coeff)) 之类的内容
  • 同时避免使用 for 循环。尝试类似lapply()

标签: r for-loop apply


【解决方案1】:

我觉得你以非 R 方式编写了这个函数。为什么需要resultsinterceptcoeff 作为GetLM 的参数?相反,让函数返回一个包含这些变量的列表:

GetLM <- function(dataframe){
     unq_clients <- as.vector(unique(dataframe$clients))
     for(i in 1:length(unq_clients)){
         new_df <- dataframe[dataframe$clients == unq_clients[i],]
         regression <- lm(a~b,data = new_df )
         results <- coef(regression)
         intercept[i] <- results[[i]][1]
         coeff[i] <- results[[i]][2]
     }
     return(list(results = results, intercept = intercept, coeff = coeff))
}

所以现在你可以这样做了:

reslist <- GetLM(dataframe = your_data_frame)
results <- reslist$results
intercept <- reslist$intercept
coeff <- reslist$coeff

【讨论】:

    【解决方案2】:

    您可以完美地继续使用您自己的代码,只需添加我在 cmets 中提到的 return() 语句。

    这里我使用lapply() 替换for 循环,并使其更通用,即使您的模型有多个独立的,您也可以以更好的方式提取它们。

    注意:我使用mtcars 解释,因为您没有与我们分享任何数据

    unq_cyl = as.vector(unique(mtcars$cyl)) # 3 unique values
    results <- lapply(seq_along(unq_cyl), function(x) {
                                        new_df = mtcars[mtcars$cyl == unq_cyl[x],]
                                        regression= lm(mpg ~ disp + wt,data = new_df )
                                        results=coef(regression)
                                        results})
    
    intercept <- sapply(results, FUN = function(i) i[names(i) %in% "(Intercept)"])
    coeff <- sapply(results, FUN = function(i) i[!(names(i) %in% "(Intercept)")])
    
    
    results
    #[[1]]
    #(Intercept)        disp          wt 
    #28.18834771  0.01914227 -3.83509580 
    #
    #[[2]]
    #(Intercept)        disp          wt 
    # 41.1350198  -0.1224733  -0.6978035 
    #
    #[[3]]
    # (Intercept)         disp           wt 
    #24.077855175 -0.002511735 -2.023137804 
    
    intercept
    #(Intercept) (Intercept) (Intercept) 
    #   28.18835    41.13502    24.07786 
    coeff
    #            [,1]       [,2]         [,3]
    #disp  0.01914227 -0.1224733 -0.002511735
    #wt   -3.83509580 -0.6978035 -2.023137804
    

    【讨论】:

    猜你喜欢
    • 2011-09-23
    • 2023-01-04
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多