I have the next query. I have a cycle
for (i in 2:n) { ... }
and it executes twice in case n = 1 for i equals 2 and then for 1, but I want this cycle isn't been executed at all in such case. I've also tried
seq(from = 2, to = 1, by = 1)
but it generates exception.
I guess than common question, but I am new in that language and wasn't able to bypass it or find workaround in internet. Thank you in advance.
Use seq_len which is safer to use
n <- 1
for (i in seq_len(n)[-1]) {
cat("Check", i, "\n")
}
#Does not print anything
n <- 4
for (i in seq_len(n)[-1]) {
cat("Check", i, "\n")
}
#Check 2
#Check 3
#Check 4
When you use 2:n and when n = 1 it gives
2:1
#[1] 2 1
hence, it runs the loop twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With