Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make R skip for 2:n cycle in case n = 1?

Tags:

range

r

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.

like image 581
LinearLeopard Avatar asked Jan 20 '26 10:01

LinearLeopard


1 Answers

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.

like image 123
Ronak Shah Avatar answered Jan 23 '26 21:01

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!