Reputation: 65
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}
Upvotes: 1
Views: 81
Reputation: 173793
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:
shapiro.test(X)$p.value < 0.05
will evaluate to either TRUE
or FALSE
as.numeric(shapiro.test(X)$p.value < 0.05)
will be 1 if the test is significant and 0 otherwise.as.numeric(t.test(X, alternative = "two.sided")$p.value < 0.05)
will return 1 if significant and 0 otherwise.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: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
Upvotes: 3
Reputation:
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
}
Upvotes: 0