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}
CodePudding user response:
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:
- The expression
shapiro.test(X)$p.value < 0.05
will evaluate to eitherTRUE
orFALSE
- This means that
as.numeric(shapiro.test(X)$p.value < 0.05)
will be 1 if the test is significant and 0 otherwise. - Similarly,
as.numeric(t.test(X, alternative = "two.sided")$p.value < 0.05)
will return 1 if significant and 0 otherwise. - If we multiply
as.numeric(shapiro.test(X)$p.value < 0.05)
by two and add it to the result ofas.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
- 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
CodePudding user response:
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
}