Home > OS >  R equivalent of Python's range() function
R equivalent of Python's range() function

Time:02-15

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().

CodePudding user response:

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!

CodePudding user response:

seq works well in this case:

> x <- NULL
> for (i in seq(x)) print(i)
> #

Thanks

  •  Tags:  
  • r
  • Related