2014-12-16 3 views
0

에있는 lm 개체의 목록을 에 lm 개의 모델 개체가 반복 될 수 있으므로이 두 개의 개체가 동일한 지 확인하는 방법을 찾고 싶습니다. 즉, 내 list을 "중복 제거"하고 싶습니다.중복 된 R

대단히 감사합니다.

문제의 예 :

## 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에서 중복 된 항목을 제외 할.

+0

'vector' 또는'data.frame'에서'duplicated()'를 사용할 수는 있지만'list's에 대한 유사점은없는 것 같습니다. 원칙적으로 두 개의 'for'루프를 중첩하고 'identical'를 사용하여 수동으로 두 항목을 테스트 할 수 있습니다 ('? identical'를 반드시 읽으십시오!). –

+0

'all.equal (lm253, lm254)'는'TRUE'를 반환하지 않으므로 중복되지 않습니다. 하지만 전화가 중복되는 것에 신경 쓰는 것 같습니까? – shadow

+0

불쌍한 영어로 유감스럽게 생각합니다. 저는 BR 출신이고 언어를 배우고 있습니다! Stephan Kolassa에게 감사드립니다. – user2154480

답변

1

많은 모델에 적합하게 만든 다음 대부분을 버리는 것은 낭비입니다. 객체 이름을 사용하면 코드를 읽기 어려워 지지만, 수식을 기반으로 모델을 구별 할 수 있습니다. 어쩌면이 도움이 될 것입니다 :

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

'duplicated'함수에 대한 메소드 선택에서 'x'인수의 평가에서 중복 된 오류 (vapply (lista_de_ajustes, function (m) Deparse ($ m call) : 오류) : 'vapply 오류 (lista_de_ajustes, 함수는 (m) Deparse ($ m call), FUN.VALUE = "a") : 값은 길이가 1이지만 FUN (X [[57])의 결과는 길이가 2 – user2154480

+0

Roland, 텍스트를 수정했습니다. 내 모델에 대한 제안이 작동하지 않았습니다. 오류가 반환되었습니다 .. – user2154480

+0

죄송합니다, 오류 메시지의 호출이 내 코드와 동일하지 않습니다 – Roland

0

롤랜드 코드에서 간단한 수정을 했으므로 저에게 효과적이었습니다. deparse(m$call)에서 deparse(formula(m))으로 바뀌 었습니다. 완성 된 수식을 비교할 수 있기 때문입니다.

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

대단히 감사합니다.