简体   繁体   中英

Writing If loop in R

I want write if loop in R in correct way when I apply this code I get an error (Error: unexpected 'else' in "else")

if(shapiro.test(X)$p.value>=0.05 && t.test(X, alternative = "two.sided")$p.value>=0.05){
  rp<-1}
else if (shapiro.test(X)$p.value>=0.05 && t.test(X, alternative = "two.sided")$p.value<0.05){
  rp<-2}
else if(shapiro.test(X)$p.value<0.05 && wilcox.test(X, mu = 0, alternative = "two.sided")$p.value>=0.05){
  rp<-3}
else if(shapiro.test(X)$p.value<0.05 && wilcox.test(X, mu = 0, alternative = "two.sided")$p.value<0.05)
{rp<-4}

This isn't a loop. It's a series of conditional statements. It's also inefficient. You only need to write each test once. You could get rp without any if statements at all by considering the following:

  1. The expression shapiro.test(X)$p.value < 0.05 will evaluate to either TRUE or FALSE
  2. This means that as.numeric(shapiro.test(X)$p.value < 0.05) will be 1 if the test is significant and 0 otherwise.
  3. Similarly, as.numeric(t.test(X, alternative = "two.sided")$p.value < 0.05) will return 1 if significant and 0 otherwise.
  4. If we multiply as.numeric(shapiro.test(X)$p.value < 0.05) by two and add it to the result of as.numeric(t.test(X, alternative = "two.sided")$p.value < 0.05) , we will get a number between 0 and 3 which represents 4 possibilities:
  • 0 means neither test was significant
  • 1 means only the t-test was significant
  • 2 means only the shapiro test was significant
  • 3 means that both tests were significant
  1. If we add one to the above numbers, we get the desired value of rp .

Therefore, your code simplifies to:

rp <- 2 * as.numeric(shapiro.test(X)$p.value < 0.05) +  
          as.numeric(t.test(X, alternative = "two.sided")$p.value < 0.05) + 1

Not really an answer, just a rearrangement of brackets. This syntax works. But is verbose.

X <- rnorm(100, 3, 1)

if (shapiro.test(X)$p.value>=0.05 && t.test(X, alternative = "two.sided")$p.value>=0.05){ 
  rp <- 1
} else if (shapiro.test(X)$p.value>=0.05 && t.test(X, alternative = "two.sided")$p.value<0.05){
  rp <- 2 
} else if (shapiro.test(X)$p.value<0.05 && wilcox.test(X, mu = 0, alternative = "two.sided")$p.value>=0.05){
  rp <- 3
} else if (shapiro.test(X)$p.value<0.05 && wilcox.test(X, mu = 0, alternative = "two.sided")$p.value<0.05){
  rp <- 4
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM