1

If I wanted to round every value in a dataframe to the nearest set of values, for example c(0, 1). How would I go about doing this?

>toRound <- c(-2, 3, 4, 1, -1, 0, .5)
>magicFunction(toRound, c(0, 1)) 
c(0, 1, 1, 1, 0, 0, 1)

>magicFunction(toRound, c(-1, 1))
c(-1, 1, 1, 1, -1, round(runif(1,min=0,max=1), 0), 1)
Parseltongue
  • 11,157
  • 30
  • 95
  • 160

1 Answers1

2

Try

toRound <- c(-2, 3, 4, 1, -1, 0, .5)
ifelse(toRound > 1, 1, ifelse(toRound < 0, 0, round(toRound)))
[1] 0 1 1 1 0 0 0

And as a function:

foo <- function(x, Min, Max) ifelse(x > Max, Max, ifelse(x < Min, Min, round(x)))
foo(toRound, -1, 1)
[1] -1  1  1  1 -1  0  0

Note that on my system a .5 is rounded to the smaller integer. If you want to round up -what your expected output suggest- you can use the solution given in this post Round up from .5 in R

Roman
  • 17,008
  • 3
  • 36
  • 49