How to check if all values are equal in a vector in r

2

I have as a function answer the RMSEA, GFI, NFI and CFI vectors that can contain all the same values. In the sequence I use the algorithm below to test the normality through the shapiro-wilk test. When the values are all equal it returns error of the form

Error in shapiro.test (RMSEA): all 'x' values are identical

and the rest of the algorithm fails because of this problem. How can I check if the values of the vectors are all equal and do not run the test in this case.

# TESTE DE NORMALIDADE

  t1 <- shapiro.test(RMSEA) 
  t2 <- shapiro.test(GFI) 
  t3 <- shapiro.test(NFI) 
  t4 <- shapiro.test(CFI) 

  estt <- as.numeric(c(t1$statistic, t2$statistic, t3$statistic,t4$statistic))
  valorp <- c(t1$p.value, t2$p.value, t3$p.value, t4$p.value)
  resultados <- cbind(estt, valorp)
  rownames(resultados) <- c("SHAPIRO-WILK RMSEA","SHAPIRO-WILK GFI","SHAPIRO-WILK NFI","SHAPIRO-WILK CFI")
  colnames(resultados) <- c("Estatística", "p")
  print(resultados)
    
asked by anonymous 05.09.2018 / 22:47

1 answer

5

You can simply compare the first element with each element using == . This will return a vector of TRUE or FALSE and all will test if all elements of this vector are equal to TRUE ( all is same as identical(TRUE, x) )

  x <- 1:10
  y <- rep(2, 10)

  all(x == x[1])
  # [1] FALSE

  all(y == y[1])
  # [1] TRUE

Ref: link

    
05.09.2018 / 23:07