在R中重复删除lm对象的列表

时间:2014-12-16 13:11:05

标签: r list duplicates

我有listlm模型对象可能会重复,所以我想找一种方法来检查这些lm个对象是否相等,如果所以他们删除它。用语言来说,我想"重复数据删除"我的list

我非常感谢任何帮助。

问题的一个例子:

## Creates outcome and predictors
outcome    <- c(names(mtcars)[1:3])
predictors <- c(names(mtcars)[4:11])
dataset    <- mtcars

## Creates model list
model_list <- lapply(seq_along((predictors)), function(n) {
  left_hand_side  <- outcome[1]
  right_hand_side <- apply(X = combn(predictors, n), MARGIN = 2, paste, collapse = " + ")
  paste(left_hand_side, right_hand_side, sep = "  ~  ")
})

## Convert model list into a verctor
model_vector <- unlist(model_list)

## Fit linear models to all itens from the vector of models
list_of_fit <- lapply(model_vector, function(x) {
  formula    <- as.formula(x)
  fit        <- step(lm(formula, data = dataset))
  fit
})

# Exclude possible missing
list_of_fit <- Filter(Negate(function(x) is.null(unlist(x))), list_of_fit)

# These models are the same in my list
lm253 <- list_of_fit[[253]];lm253
lm254 <- list_of_fit[[254]];lm254
lm255 <- list_of_fit[[255]];lm255

我想排除list_of_fit中的重复条目。

2 个答案:

答案 0 :(得分:1)

装入这么多模型然后扔掉大部分模型似乎很浪费。您的对象名称使您的代码难以阅读,但似乎您的模型可以根据其公式进行区分。也许这会有所帮助:

lista_de_ajustes[!duplicated(vapply(lista_de_ajustes, 
                                    function(m) deparse(m$call), 
                                    FUN.VALUE = "a"))]

答案 1 :(得分:0)

我在你的代码Roland中做了一个简单的修改,所以它对我有用。 我从deparse(m$call)更改为deparse(formula(m)),因此我可以比较完整的公式。

lista_de_ajustes[!duplicated(vapply(lista_de_ajustes, function(m) deparse(formula(m)), FUN.VALUE = "a"))]

非常感谢!