Comparación de dos vectores en una sentencia if


Quiero poner la condición stop dentro de una función. La condición es que si el primer y segundo elementos deben coincidir perfectamente en orden y longitud.

A <- c("A", "B", "C", "D")
B <- A
C <- c("A", "C", "C", "E")

> A == B
[1] TRUE TRUE TRUE TRUE

Esta es una buena situación para seguir adelante

> A == C

[1]  TRUE  FALSE TRUE FALSE

Dado que hay un falso esta condición para detener y salida que la condición doesnot mantener en 2 y 4a columna.

if (A != B) {
           stop("error the A and B does not match at column 2 and 4"} else {
            cat ("I am fine") 
                }
Warning message:
In if (A != B) (stop("error 1")) :
  the condition has length > 1 and only the first element will be used

¿Me estoy perdiendo algo obvio ? También puedo mostrar dónde están las posiciones de error ?

Author: Paul Hiemstra, 2012-04-29

3 answers

all es una opción:

> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")

> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE

Pero es posible que tenga cuidado con el reciclaje:

> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE

La documentación para length dice que actualmente solo produce un entero de longitud 1, pero que puede cambiar en el futuro, por lo que envolví la prueba de longitud en all.

 50
Author: Aaron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-30 01:35:09

Son idénticos?

> identical(A,C)
[1] FALSE

Qué elementos no están de acuerdo:

> which(A != C)
[1] 2 4
 22
Author: Matthew Lundberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-29 18:53:14

Probablemente usaría all.equal y which para obtener la información que desea. No se recomienda usar all.equal en un bloque if...else por alguna razón, así que lo envolvemos en isTRUE(). Ver ?all.equal para más:

foo <- function(A,B){
  if (!isTRUE(all.equal(A,B))){
    mismatches <- paste(which(A != B), collapse = ",")
    stop("error the A and B does not match at the following columns: ", mismatches )
  } else {
    message("Yahtzee!")
  }
}

Y en uso:

> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) : 
  error the A and B does not match at the following columns: 2,4
 7
Author: Chase,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-29 19:02:07