【问题标题】:GLM insert vector using the string of the vector, rather than the vector itselfGLM 使用向量的字符串插入向量,而不是向量本身
【发布时间】:2019-11-25 12:06:47
【问题描述】:

我正在创建一个函数来运行我的所有分析,作为一种简化 600 行代码以避免错误的方法。我在 GLM 的线路上遇到问题。我对过滤数据帧进行了一些分析,但是当我向量化 DV 和 ME 时,它们来自已经存在的数据帧(my_data$Hire,my_data$Con)。我需要以这样的方式传递这些值,以使 R 能够从新创建的数据帧 - GM 中识别出它们是正确的 DV 和 ME。

calculatemodels <- function(type, DV, ME, ME2, MD, df, test, MA_data, model, number, samplename){

  if (type == "A1"){
    GM <- my_data %>% filter(Gender == 1)
    m <- glm(DV ~ ME, data=GM) # problem here, need to pass DV and ME vectors correctly.
    MA_data <- CollectDEffect(test, m, MA_data, namestring(ME), model, number, samplename) 
  }

  return(MA_data)
}

MA_data <- calculatemodels("A1", my_data$Hire, my_data$Con, , , my_data, 
                           "", MA_data, "", "1", "full")

我尝试使用 get 和 paste,但它不起作用。简而言之,我需要传递 DV 和 ME 的名称,并让函数识别这些是模型的向量,而不是传递已经附加到数据帧的向量,即 my_data$Hire

【问题讨论】:

    标签: r glm


    【解决方案1】:

    据我了解,您正在尝试将模型的成分作为向量传递并在它们上运行 glm 模型。

    这里有几个问题。首先,my_data 不是函数变量。我猜它存在于您的全球环境中。其次,您需要根据列名创建一个公式 (as.formula) 并将其用作模型的输入:

    calculatemodels <- function(type, DV, ME, ME2, MD,
                                df, test, MA_data,
                                model, number,samplename){
    
      if (type == "A1"){
        GM <- my_data %>% filter(Gender == 1)
        glm_model <- as.formula(paste0(DV,"~",ME))
        m <- glm(glm_model, data=GM) # problem here, need to pass DV and ME vectors correctly.
        MA_data <- CollectDEffect(test, m, MA_data, namestring(ME), model, number, samplename) 
      }
    
      return(MA_data)
    }
    

    您需要使用列名(Hire 和 Con)作为函数的输入值:

    MA_data <- calculatemodels("A1", "Hire", "Con", , , my_data, 
                               "", MA_data, "", "1", "full")
    

    希望这能解决问题。

    【讨论】:

    • 这样一个美丽而优雅的解决方案。由于您的建议,我从函数中删除了 90% 的代码 - 起首部分!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多