GLM 使用向量的字符串而不是向量本身插入向量

GLM insert vector using the string of the vector, rather than the vector itself

我正在创建一个函数,它将 运行 我的所有分析,作为一种简化 600 行代码以避免错误的方法。我在使用 GLM 时遇到问题。我对过滤数据帧进行了一些分析,但是当我向量 DV 和 ME 时,它们来自已经存在的数据帧(my_data$Hiremy_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")

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

据我了解,您正试图将模型的成分作为向量传递,并 运行 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)
}

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

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

希望这能解决问题。