Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R equivalent of Python's range() function

Tags:

r

Is there an R equivalent to Python's range function?

In Python I can do this:

for i in range(1, 4):
    print(i)

1
2
3

and especially this:

for i in range(1, 0):
    print(i)

# prints nothing!

Meanwhile in R:

> 1:0

[1] 1 0

also

> c(1:0)

[1] 1 0

and

> seq(from=1, to=0)

[1] 1 0 

I need a function that given as input a min and a max returns a vector of increasing integers from min to max s.t. if max < min returns an empty vector.

This question on SO is different from mine. Talks about strings and seq() which, as shown above, is not equivalent to range().

like image 813
IDK Avatar asked Nov 23 '25 23:11

IDK


1 Answers

There is no exact equivalent. As noted, seq doesn't work because the by argument is automatically set with the correct sign, and generates an error if you try to explicitly pass a positive sign when to < from. Just create a very simple wrapper if you need to have the exact match.

py_range <- function(from, to) {
  if (to <= from) return(integer(0))
  seq(from = from, to = to - 1)
}

py_range(1, 4)
#> [1] 1 2 3
py_range(1, 0)
#> integer(0)
py_range(1, 1)
#> integer(0)

These will work in a loop with printing as you desire.

for (i in py_range(1, 4)) {
  print(i)
}
#> [1] 1
#> [1] 2
#> [1] 3

for (i in py_range(1, 0)) {
  print(i)
}
#> Nothing was actually printed here!

for (i in py_range(1, 1)) {
  print(i)
}
#> Nothing was actually printed here!
like image 198
caldwellst Avatar answered Nov 26 '25 11:11

caldwellst



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!