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

Asked

Viewed 653 times

2

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

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

and the rest of the algorithm fails because of this problem. How can I verify that the values of the vectors are all equal and 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)

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 test whether all elements of this vector are equal to TRUE (all is the 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: https://stat.ethz.ch/pipermail/r-help/2005-August/078129.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.